Pytho正则表达式-match
代碼:
#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
以上實例執行結果如下:
matchObj.group() : Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2) : smarter
主要解釋下 ?r'(.*) are (.*?) .*'
首先,這是一個字符串,前面的一個r表示字符串為非轉義的原始字符串,讓編譯器忽略反斜杠,也就是忽略轉義字符。但是這個字符串里沒有反斜杠,所以這個r可有可無。
(.*) 第一個匹配分組, ? .* ?代表匹配除換行符之外的所有字符,即任意字符即可
(.*?)第二個匹配分組,.*?后面多個問號,代表非貪婪模式,也就是說只匹配符合條件的最少字符
后面的一個.* ?沒有括號包圍,所以不是分組,匹配效果和第一個一樣,但是不計入匹配結果中,只有加括號的才會返回到匹配結果中
matchObj.group() 等同于?matchObj.group(0),表示匹配到的完整文本字符
matchObj.group(1) 得到第一組匹配結果,也就是(.*)匹配到的
matchObj.group(2) 得到第二組匹配結果,也就是(.*?)匹配到的
這里對新手還有個問題,matchObj.group(3)會報錯,因為只有匹配結果中只有兩組,所以填3時會報錯。
下面是修改后的代碼 ?,一看便懂
#!/usr/bin/python import re line = "Cats are smarter than dogs hahaha" matchObj = re.match(r'(.*) are (.*?) than (.*) ha', line, re.M | re.I) if matchObj:print "matchObj.group() : ", matchObj.group()print "matchObj.group(1) : ", matchObj.group(1)print "matchObj.group(2) : ", matchObj.group(2)print "matchObj.group(3) : ", matchObj.group(3) else:print "No match!!"
結果:
D:\python\python.exe D:/pycharm/workspace/test01.py
matchObj.group() : ?Cats are smarter than dogs ha
matchObj.group(1) : ?Cats
matchObj.group(2) : ?smarter
matchObj.group(3) : ?dogs
總結
以上是生活随笔為你收集整理的Pytho正则表达式-match的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 聊聊自己的高效学习方法~
- 下一篇: 武汉火神山医院正式交付,华为提供多项技术