讲一些正则表达式的细节问题

一、为什么使用原生字符串

r''指的是原生字符串,目的是将Python中反斜杠的含义取消,避免发生冲突
例一:目标字符串为'ab\bc\cd',想要匹配'ab\'
我们知道一个\需要用两个\\来匹配,正则表达式应改写为ab\\,进而在Python中应改写为"ab\\\\"。
一串字符需要经过Python解释器的转义和正则表达式的转义,这样做显然比较麻烦。所以我们可以使用r''原生字符串跳过Python的转义。
例二:目标字符串为'abc word 123',想要匹配单词'word'。我们需要注意:\b在Python中表示退格,而在正则中表示匹配一个单词的边界位置。
所以正则表达式必须写为r'\bword\b'。
因此在写正则表达式时,最好写上原生标记r''。

import re
pattern = re.compile(r'\bword\b')
print(re.search(pattern, 'abc word 123'))
#输出
#<_sre.SRE_Match object; span=(4, 8), match='word'>


str="ab\\bc\\cd"
res1=re.match("ab\\\\",str)
print(str,res1)
#输出ab\bc\cd <_sre.SRE_Match object; span=(0, 3), match='ab\\'>

二、.*?有什么含义

.  匹配除\n以外的任意字符
* 前面一个字符出现0次或多次
?表示非贪婪匹配
a.*?b匹配最短的,以a开始,以b结束的字符串。
对于aabab,它会匹配到aab和ab。

三、非捕获组是什么?以及findall匹配分组时的特点?\b如何匹配单词边界?

import re
str='ababab abbabb aabaab'
res61=re.findall(r'\b(?:ab)+\b',str)
res62=re.findall(r'(ab)+',str)#将字符串所有ab都匹配出来,因为有分组,只显示分组内容
res63=re.findall(r'\b(ab)+\b',str)#匹配出单词ababab,只显示分组内容
res64=re.findall(r'(?:ab)+',str)#将字符串所有ab都匹配出来,无捕获组即显示全部内容
print(res61,res62,res63,res64)
#输出
#['ababab'] ['ab', 'ab', 'ab', 'ab', 'ab'] ['ab'] ['ababab', 'ab', 'ab', 'ab', 'ab']


res7=re.findall(r'(\d{3}-)?(\d{7})','020-8888888\n010-1234567')
print(res7)
res8=re.findall(r'(?:\d{3}-)?(?:\d{7})','020-8888888\n010-1234567')
print(res8)
#输出
#[('020-', '8888888'), ('010-', '1234567')]
#['020-8888888', '010-1234567']


str = 'I have a dog , I have a cat'
res4=re.findall(r'I have a (?:dog|cat)',str)
print(res4)
res5=re.findall(r'I have a dog|cat',str)
print(res5)
# 输出:['I have a dog', 'I have a cat']
# ['I have a dog', 'cat']


str=".8CAT@"
res9=re.findall(r'\b\w+\b',str)
print(res9)
# 输出:['8CAT']

四、re.I、re.S、re.M的用法?

re.I  忽略大小写
re.M  改变^和$的行为,^$默认只能匹配一行的内容,
改变后可以匹配多行
re.S  改变.的行为,使得.能匹配换行

a = 'This is the first line.\nThis is the second line.\nThis is the third line.'
q = re.match(r'This.*line.', a, flags=re.S)
print(q.group(0))
# 输出:This is the first line.
# This is the second line.
# This is the third line.

a = 'This is the first line.\nThis is the second line.\nThis is the third line.'
print(re.findall(r'^This.*line.$', a,flags=re.M))
# 输出:
# ['This is the first line.', 'This is the second line.', 'This is the third line.']

五、finditer、sub、split如何使用?

res3 = re.finditer(r'\d+','aa123bb456cc')  #返回Match对象的一个迭代器

content = "123abc456"
new_content = re.sub(r'\d+', '#', content)
print(new_content)
res10 = re.split(r'\d+','one1two2three3four4')
print(res10)
# 输出:#abc#
# ['one', 'two', 'three', 'four', '']

猜你喜欢

转载自blog.csdn.net/q354636996/article/details/89493835
今日推荐