说说 Python 正则表达式中的通配符

在 Python 正则表达式中,.(句点)字符被称为“通配符”。它会匹配除了换行符之外的所有字符。

1 基本用法

ha_regex=re.compile(r'ha.')
result=ha_regex.findall('Hey doc. Well, I think I might need glasses. I’m getting headaches, and I really struggle to see things that are far away. But I have always had 20/20 vision. ')
print(result)

运行结果:

[‘hat’, ‘hav’, ‘had’]

因为句点通配符只匹配一个字符,所以上述示例中的 have 只匹配除 hav。

如果想匹配真正的句点, 就必须使用倒斜杠字符进行转义: \

ha_regex=re.compile(r'.\.')
result=ha_regex.findall('Hey doc. Well, I think I might need glasses. I’m getting headaches, and I really struggle to see things that are far away. But I have always had 20/20 vision. ')
print(result)

运行结果:

[‘c.’, ‘s.’, ‘y.’, ‘n.’]

2 匹配所有字符

可以用点-星来匹配所有字符。因为句点字符表示“除换行之外所有单个字符”,而星号字符表示“前
面字符出现零次或多次”。组合起来就是匹配除换行之外的所有字符。

doc_regex=re.compile(r'除了(.*)同时还可以(.*)')
result=doc_regex.findall('家电实体店要以门店为圆心,构建多极化的经营体系。除了从线下到线上,依靠家电工厂、第三方电商开放平台等资源发展线上微店等,同时还可以从零售一条腿走路,向工程、批发、直营、促销、团购等多业态布局。')
print(result)

运行结果:

[(‘从线下到线上,依靠家电工厂、第三方电商开放平台等资源发展线上微店等,’, ‘从零售一条腿走路,向工程、批发、直营、促销、团购等多业态布局。’)]

点-星模式默认使用“贪心” 模式,即尽可能多地匹配文本。使用点-星加问号符,就可以改用“非贪心” 模式。请看下例:

no_greedy_regex=re.compile(r'case.*?end')
print(no_greedy_regex.search("case xxx end xxx end"))
greedy_regex=re.compile(r'case.*end')
print(greedy_regex.search("case xxx end xxx end"))

运行结果:

<re.Match object; span=(0, 12), match=‘case xxx end’>
<re.Match object; span=(0, 20), match=‘case xxx end xxx end’>

3 匹配换行

我们可以通过传入 re.DOTALL 作为 re.compile() 的第二个参数,这样就可以让句点通配符匹配所有字符, 包括换行字符。

no_new_line_regex = re.compile('.*')
print(no_new_line_regex.search('DC宇宙中最强大的超级英雄是谁?\n超人,蝙蝠侠还是没有任何弱点的神奇女侠?'))
new_line_regex = re.compile('.*', re.DOTALL)
print(new_line_regex.search('DC宇宙中最强大的超级英雄是谁?\n超人,蝙蝠侠还是没有任何弱点的神奇女侠?'))

运行结果:

<re.Match object; span=(0, 16), match=‘DC宇宙中最强大的超级英雄是谁?’>
<re.Match object; span=(0, 37), match=‘DC宇宙中最强大的超级英雄是谁?\n超人,蝙蝠侠还是没有任何弱点的神奇女侠?’>

发布了601 篇原创文章 · 获赞 668 · 访问量 88万+

猜你喜欢

转载自blog.csdn.net/deniro_li/article/details/103747048