一、正则表达式的基本概念

1.1 字符匹配

正则表达式的基本功能是字符匹配。它允许你指定一个模式,然后对文本进行扫描,找出所有符合该模式的字符串。

1.2 元字符

元字符是正则表达式中具有特殊意义的符号,它们用于定义匹配的规则。常见的元字符包括:

  • .:匹配除换行符以外的任意字符。
  • *:匹配前面的子表达式零次或多次。
  • +:匹配前面的子表达式一次或多次。
  • ?:匹配前面的子表达式零次或一次。
  • []:匹配括号内的任意一个字符(字符类)。
  • [^]:匹配不在括号内的任意一个字符(否定字符类)。
  • ():分组,可以用来引用分组匹配的内容。

1.3 定位符

定位符用于指定匹配的位置,常见的定位符包括:

  • ^:匹配输入字符串的开始位置。
  • $:匹配输入字符串的结束位置。
  • *:匹配前一个字符出现的零次或多次。
  • +:匹配前一个字符出现一次或多次。
  • ?:匹配前一个字符零次或一次。
  • {m,n}:匹配前面的子表达式m次或n次。

二、Python正则表达式库

Python中,正则表达式通过re模块实现。以下是一些常用的re模块函数:

  • re.match(pattern, string):从字符串的起始位置匹配正则表达式。
  • re.search(pattern, string):在字符串中搜索匹配正则表达式的子串。
  • re.findall(pattern, string):找到字符串中所有匹配正则表达式的子串。
  • re.sub(pattern, replacement, string):将字符串中所有匹配正则表达式的子串替换为指定的字符串。

三、正则表达式应用实例

3.1 提取电子邮件地址

import re

email = "my_email@example.com"
pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
result = re.findall(pattern, email)
print(result)  # 输出:['my_email@example.com']

3.2 提取URL

import re

text = "Visit https://www.example.com for more information."
pattern = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+'
result = re.findall(pattern, text)
print(result)  # 输出:['https://www.example.com']

3.3 提取图片链接

import re

text = "Here is an image: <img src='https://example.com/image.jpg'>"
pattern = r'<img\s+src=["\'](.*?)["\']'
result = re.findall(pattern, text)
print(result)  # 输出:['https://example.com/image.jpg']

四、总结