1. 程式人生 > >正則表示式學習程序(一)re.match()

正則表示式學習程序(一)re.match()

#正則表示式學習筆記
import re

"""
.匹配任意字元 除換行符
{n}精確匹配前面n個表示式
\s 匹配任意的空白字元
\w 匹配字母數字及下劃線
.* 匹配任意除換行符之外的字元
{n}    精確匹配n個前面表示式。
+  匹配1個或多個的表示式。
( )    匹配括號內的表示式
?  匹配0個或1個由前面的正則表示式定義的片段,非貪婪方式
re.S 如果不使用re.S引數,則只在每一行內進行匹配,如果一行沒有,就換下一行重新開始,不會跨行
"""
#re.match() 嘗試從字串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match()返回none
#用法:re.match(pattern,string ,flags=0)  flags標誌位,用於控制正則表示式的匹配方式,如:是否區分大小寫,多行匹配等等。
""" 1.string與pattern完全相同,成功匹配 2.string雖然多出一個字母,但pattern匹配完成時,匹配成功,後面的字元不再匹配。 3.string匹配到最後一個字母時,發現仍然無法完全匹配,匹配失敗。 """ content ='Hello 123 4567 World_This is a Regex Demo' contents ='Hello 123 4567 World_This is a Regex Demo ada' result = re.match('Hello\s\d{3}\s\d{4}\s\w{10}.*Demo$', content) print
(result) print(type(result))#<class '_sre.SRE_Match'> print(len(content)) print(result.group())#返回匹配結果 Hello 123 4567 World_This is a Regex Demo print(result.span())#輸出範圍 (0,41) result = re.match('Hello\s\d{3}\s\d{4}\s\w{10}.*Demo', contents) print(result) #結果:<_sre.SRE_Match object; span=(0, 41), match='Hello 123 4567 World_This is a Regex Demo'>
#泛匹配 result = re.match('Hello.*Demo$',content) print(result) #<_sre.SRE_Match object; span=(0, 41), match='Hello 123 4567 World_This is a Regex Demo'> print(result.group()) #Hello 123 4567 World_This is a Regex Demo #匹配目標 content ='Hello 1234567 World_This is a Regex Demo' result = re.match('Hello\s(\d+)\sWorld.*Demo$',content) #匹配括號裡面的 print("############") print(result.group()) print(result.group(1)) #1234567 print(result.span()) #(0,40) #貪婪匹配 result = re.match('He.*(\d+).*Demo$',content) print(result.group()) print(result.group(1)) #輸出7 前面的1-6被.*匹配,貪婪模式 #非貪婪模式 result1 = re.match('He.*?(\d+).*Demo$',content) result2 = re.match('He.*?(\d+).*?Demo$',content) print(result2.group(1)) # print(result1.group(1)) #輸出1234567 #匹配模式 content = """Hello 1234567 World_This is a Regex Demo """ result1 = re.match('^He.*?(\d+).*?Demo$', content) print(result1) #輸出None 因為有換行符 result2 = re.match('^He.*?(\d+).*?Demo$', content,re.S) print(result2) #輸出None print(result2.group(1))#1234567 #轉義 content = 'price is $5.00' result = re.match('price is $5.00',content) print(result) #None result = re.match('price is \$5\.00', content) print(result)#<_sre.SRE_Match object; span=(0, 14), match='price is $5.00'> """ 總結:儘量使用泛匹配,使用()得到匹配目標,儘量使用非貪婪模式、有換行符就用re.S """