本篇主要介绍正则表达式中的其他元字符,本人水平有限,难免出现错误,欢迎指正。
1、其他元字符
示例:
importre
#行首匹配zhi
print(re.search("^zhi","zhi shu fen xi"))
#行尾匹配xi
print(re.search("xi$","zhi shu fen xi"))
#多行行首匹配zhi,2个匹配成功
print(re.findall("^zhi","zhi shu fen xi\nzhi shu fen xi", re.M))
#多行行首匹配zhi,1个匹配成功
print(re.findall("\Azhi","zhi shu fen xi\nzhi shu fen xi", re.M))
#多行行尾匹配xi,2个匹配成功
print(re.findall("xi$","zhi shu fen xi\nzhi shu fen xi", re.M))
#多行行尾匹配xi,1个匹配成功
print(re.findall("xi\Z","zhi shu fen xi\nzhi shu fen xi", re.M))
#匹配单词边界,匹配成功
print(re.search(r"ab\b","tab"))
#匹配单词边界,匹配失败
print(re.search(r"ab\b","sabs"))
#匹配非单词边界,匹配失败
print(re.search(r"ab\B","tab"))
#匹配非单词边界,匹配成功
print(re.search(r"ab\B","sabs"))
输出:
['zhi', 'zhi']
['zhi']
['xi', 'xi']
['xi']
None
None
2、匹配多个字符
说明:下标中的abc表示普通字符,mn表示普通整数
示例:
importre
#只能匹配到一个aa
print(re.findall(r"(aa)","aaa"))
#尽可能少的匹配a,最后的''表示匹配到0个a
print(re.findall(r"a?","aaa"))
#尽可能多的匹配a
print(re.findall(r"a*","aaabaa"))
#尽可能多的匹配a
print(re.findall(r"a+","aaabaaaaaa"))
#匹配3个a
print(re.findall(r"a","aaabaa"))
#至少匹配3个a,尽可能多的匹配
print(re.findall(r"a","aaaaabaaacaa"))
#匹配3-5个a
print(re.findall(r"a","aaabaaaaaacaa"))
#匹配z或Z
print(re.findall(r"(z|Z)","zhi_ZhiZ"))
print(re.findall(r"((z|Z)hi)","zhi_ZhiZ"))
输出:
['aa']
['a', 'a', 'a', '']
['aaa', '', 'aa', '']
['aaa', 'aaaaaa']
['aaa']
['aaaaa', 'aaa']
['aaa', 'aaaaa']
['z', 'Z', 'Z']
[('zhi', 'z'), ('Zhi', 'Z')]
领取专属 10元无门槛券
私享最新 技术干货