正则表达式里match和group某用法

今天在用正则时,发现match和group里面一个很容易疏忽的点。

import re
s= 'this is a number 23564-235-22-423'
r=re.match('.+?(\d+-\d+-\d+-\d+)',s)  #匹配
a=r.group(1)   #提取
print(a)

运行结果:

23564-235-22-423

如果改成:

import re
s= 'this is a number 23564-235-22-423'
r=re.match('.+(\d+-\d+-\d+-\d+)',s)  #匹配
a=r.group(1)   #提取
print(a)

运行结果:

4-235-22-423

因为

.+ 是匹配任意多个字符,再加?是非贪婪格式,所以第一段程序里面.+?是非贪婪模式,只匹配了this is a number,使
(\d+-\d+-\d+-\d+)得到了满足匹配形式的最多数字;第二段程序.+是贪婪模式,匹配了this is a number 2356,只让(\d+-\d+-\d+-\d+)得到了满足匹配形式的最少数字
如果group()内不填数字,则为所有字符:

import re
s= 'this is a number 23564-235-22-423'
r=re.match('.+(\d+-\d+-\d+-\d+)',s)  #匹配
a=r.group()   #提取

print(a)

this is a number 23564-235-22-423

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章