跳转至

python正则

标志 描述 示例
re.I 忽略大小写匹配。 re.search(r'apple', 'Apple', re.I)
re.L 依赖于当前环境的特殊字符集,包括 \w, \W, \b, \B, \s, \S。 re.match(r'\w+', '你好', re.L)
re.M 多行模式,^ 匹配字符串的开始位置以及每行的开始位置,$ 匹配字符串的结束位置以及每行的结束位置。 re.findall(r'^\d+', '1. first\n2. second', re.M)
re.S 匹配任意字符,包括换行符。 re.search(r'.+', 'line1\nline2', re.S)
re.U 依赖于 Unicode 字符属性数据库的特殊字符集,包括 \w, \W, \b, \B, \d, \D, \s, \S。 re.match(r'\w+', '你好', re.U)
re.X 忽略空格和 # 后面的注释,增加正则表达式的可读性。 re.findall(r'apple', 'apple # this is a fruit', re.X)
with open(r'config.cfg',encoding='utf-8',mode='r') as f:
    lines = f.read()

预编译

c_txt = re.compile('\\d+')

re.search():匹配整个字符串,并返回第一个成功的匹配。如果匹配失败,则返回None

1
2
3
4
5
6
7
pysq = re.search('\\d+',lines).group() # group() 获取匹配的文本
print(pysq)
pysq.start() # 匹配的起始位置 序号
pysq.end() # 匹配的结束位置 序号
pysq.span() # 返回元组 匹配的[开始,结束]位置 序号

pysq == c_txt.search(lines).group()

findall

re.findall():匹配整个字符串,并返回所有成功的匹配。如果匹配失败,则返回空列表。

re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest')
re.findall(r'(\w+)=(\d+)', 'set width=20 and height=10')

match

re.match():匹配字符串

fullmatch

re.match():如果整个 string 与正则表达式 pattern 匹配,则返回相应的 Match。如果匹配失败,则返回None。