1. 匹配与查找类方法

re.search(pattern, string, flags=0)
  • 作用:在字符串中搜索第一个匹配的模式。
  • 返回:若匹配成功,返回Match对象;否则返回None
  • 示例

    python

    运行

    import re
    text = "Hello, World!"
    match = re.search(r"World", text)
    if match:
        print("找到匹配:", match.group())  # 输出: 找到匹配: World
    

re.match(pattern, string, flags=0)
  • 作用:从字符串的开头开始匹配模式。
  • 返回:若匹配成功,返回Match对象;否则返回None
  • 示例

    python

    运行

    match = re.match(r"Hello", text)  # 匹配成功
    print(match.group())  # 输出: Hello
    
    match = re.match(r"World", text)  # 匹配失败(不是开头)
    print(match)  # 输出: None
    
re.findall(pattern, string, flags=0)
  • 作用:查找字符串中所有匹配的模式,并返回一个列表。
  • 示例

    python

    运行

    text = "apple, banana, cherry"
    fruits = re.findall(r"\w+", text)
    print(fruits)  # 输出: ['apple', 'banana', 'cherry']
    
re.finditer(pattern, string, flags=0)
  • 作用:与findall类似,但返回一个迭代器,每个元素是一个Match对象。
  • 示例

    python

    运行

    matches = re.finditer(r"\w+", text)
    for match in matches:
        print(match.group())  # 依次输出: apple, banana, cherry
    

2. 替换与分割类方法

re.sub(pattern, repl, string, count=0, flags=0)
  • 作用:将字符串中匹配的模式替换为指定内容。
  • 参数
    • repl:可以是字符串或函数。
    • count:最多替换次数(默认全部替换)。
  • 示例

    python

    运行

    text = "Hello, World!"
    new_text = re.sub(r"World", "Python", text)
    print(new_text)  # 输出: Hello, Python!
    
re.subn(pattern, repl, string, count=0, flags=0)
  • 作用:与sub类似,但返回一个元组(新字符串, 替换次数)
  • 示例

    python

    运行

    result = re.subn(r"o", "O", text)
    print(result)  # 输出: ('HellO, WOrld!', 2)
    
re.split(pattern, string, maxsplit=0, flags=0)
  • 作用:根据匹配的模式分割字符串,返回分割后的列表。
  • 示例

    python

    运行

    text = "apple,banana;cherry"
    fruits = re.split(r"[;,]", text)
    print(fruits)  # 输出: ['apple', 'banana', 'cherry']
    

3. 编译与高级用法

re.compile(pattern, flags=0)
  • 作用:将正则表达式编译为模式对象,提高重复使用效率。
  • 示例

    python

    运行

    pattern = re.compile(r"\d+")  # 编译匹配数字的模式
    print(pattern.findall("123 apples and 456 bananas"))  # 输出: ['123', '456']
    
Match对象的方法

当使用searchmatchfinditer返回Match对象后,可以使用以下方法:

  • match.group():返回匹配的字符串。
  • match.start():返回匹配的起始位置。
  • match.end():返回匹配的结束位置。
  • match.span():返回(start, end)元组。

4. 标志位(flags)

在上述方法中,flags参数可用于修改匹配行为,常见的标志有:

  • re.IGNORECASE/re.I:忽略大小写。
  • re.MULTILINE/re.M:多行模式,影响^$的匹配。
  • re.DOTALL/re.S.匹配任意字符(包括换行符)。

总结

方法 作用 返回值类型
search 搜索第一个匹配 MatchNone
match 从开头匹配 MatchNone
findall 查找所有匹配 列表
finditer 查找所有匹配(迭代器) 迭代器
sub 替换匹配内容 新字符串
subn 替换匹配内容并返回次数 (新字符串, 次数)
split 根据模式分割字符串 列表
compile 编译正则表达式为模式对象 模式对象

这些方法覆盖了正则表达式的核心应用场景,包括查找、替换、分割和复杂匹配。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐