正则表达式

· 笔记

5 min

正则表达式(Regular Expression, Regex)是一种用于匹配字符串模式的强大工具。它使用一套符号规则描述文本结构,用于搜索、提取、验证和替换文本。

Eg.

1import re
2
3re.findall(r'\d+', "User ID: 114514, Pwd: 1919810")

Regex 语法简介

Regex 表达式中有两类字符:

  1. 字面量:直接匹配字符本身:

    1re.findall("abc|cde", "abcdefgabcdefg")
    
  2. 元字符(特殊符号):Regex 中有一些符号具有特殊意义:.^$*+?{}[]()\|

元字符匹配规则

  • .:匹配任意单个字符(除换行)
  • ^:匹配行首
  • $:匹配行尾
  • \:转义特殊字符
  • |:逻辑“或”

重复限定符(量词)

  • *:重复 0 次或多次
  • +:重复 1 次或多次
  • ?:重复 0 次或 1 次
  • {n}:重复 n 次
  • {n,}:至少重复 n 次
  • {n,m}:重复 n 到 m 次之间

字符类

字符类用于匹配一组可能的字符

  • [abc]:匹配 a 或 b 或 c
  • [^abc]:匹配非 a、b、c 的字符
  • [a-z]:匹配小写字母
  • [0-9]:匹配数字
  • [A-Za-z0-9_]:匹配字母、数字、下划线(等价于 \w)

简写字符类

  • \d:数字 [0-9]
  • \D:非数字
  • \w:字母、数字、下划线
  • \W:非字母数字
  • \s:空白字符(空格、制表符、换行)
  • \S:非空白字符

分组与反向引用

使用括号 () 进行分组:

位置锚点

  • ^:匹配字符串开头
  • $:匹配字符串结尾
  • \b:匹配单词边界
  • \B:匹配非单词边界

Eg.

\bcat\b

匹配完整单词 “cat”,而非 “concatenate”。

贪婪与惰性匹配

  • .*:贪婪匹配(尽可能多地匹配)
  • .*?:惰性匹配(尽可能少地匹配)

Python re 模块常用函数

  1. re.search(pattern, string, flags=0):在整个字符串中查找第一个匹配,并返回一个 re.Match 对象;若无匹配,则返回 None

    1re.search(r'world', 'hello world!') # <re.Match object; span=(6, 11), match='world'>
    
  2. re.match(pattern, string, flags=0):检查字符串开头是否匹配。类似 re.search,但仅在字符串开头匹配

    1re.match('hello', '!hello world!')  # None
    
  3. re.findall(pattern, string, flags=0):返回所有非重叠匹配项列表。

    1re.findall(r'\w{3}', 'cat bat mat rat') # ['cat', 'bat', 'mat', 'rat']
    
  4. re.finditer(pattern, string, flags=0):返回一个迭代器,其中包含所有匹配结果的 re.Match 对象。

    1for m in re.finditer(r'\d+', 'a1b22c333'):
    2    print(m)
    3# <re.Match object; span=(1, 2), match='1'>
    4# <re.Match object; span=(3, 5), match='22'>
    5# <re.Match object; span=(6, 9), match='333'>
    
  5. re.sub(pattern, repl, string, count=0, flags=0):从左侧开始将 pattern 匹配的内容替换成 repl,且替换不重叠。count 表示匹配次数,默认 0 表示全部替换

    1re.sub(r'-', '/', '2025-10-19-12-33', count=2)  # '2025/10/19-12-33'
    

    repl 支持函数替换,但函数输出必须是正则表达式

    1def repl_func(m):
    2    return f"[{m.group(0)}]"
    3re.sub(r'\d+', repl_func, 'abc123def')  # 'abc[123]def'
    
  6. re.split(pattern, string, maxsplit=0, flags=0):按模式分割字符串。maxsplit 表示最多分割点数

    1re.split(r'[,; ]+', 'a,b; c d', maxsplit=2) # ['a', 'b', 'c d']
    

常用匹配标志(flags)

  • re.I / re.IGNORECASE:忽略大小写
  • re.M / re.MULTILINE:多行匹配模式
  • re.S / re.DOTALL. 可以匹配换行符
  • re.X / re.VERBOSE:允许多行书写与注释
  • re.A / re.ASCII:仅匹配 ASCII 字符
1re.search(r'abc', 'ABC', re.I)  # <re.Match object; span=(0, 3), match='ABC'>

Match 对象常用方法

1m = re.search(r'\d+', 'abc123xyz')
2
3m.group()   # '123'
4m.start()   # 3
5m.end()     # 6
6m.span()    # (3, 6)