1.1 介紹
福哥今天要給大家講講Python的正則表達式的使用技巧,正則表達式(Regular expressions)就是通過一系列的特殊格式的匹配符號去描述一個字符串的工具。
使用正則表達式可以快速檢測字符串的格式,也可以從字符串裏面查找出符合特定規則的字符串片斷,還可以將字符串按照特定的規則替換或者重組成新的字符串。
2. 正則表達式
2.1 表達式
2.1.1 re.compile
使用re.compile方法可以定義一個pattern,用來使用其他方法調用這個pattern。
url = "https://tongfu.net/home/35.html"
pattern = re.compile(r"tongfu.net", re.I)
print(re.findall(pattern, url))

2.1.2 re.template
re.template方法和re.compile方法類似,可以達到相同的目的。
url = "https://tongfu.net/home/35.html"
pattern = re.template(r"tongfu.net", re.I)
print(re.findall(pattern, url))
2.2 匹配
2.2.1 re.match
re.match可以實現使用pattern去匹配字符串,結果是一個對象,可以有很多功能可以使用。
re.match是從字符串開頭進行匹配的,pattern如果不包含字符串開頭部分的話,匹配一定會失敗!
url = "https://tongfu.net/home/35.html"
match = re.match(r"https://([^/]+)/home/(d+).html", url)
print(match.group())
print(match.groups())

2.2.2 re.search
re.search和re.match類型,區別在於re.search不是從字符串開頭匹配的。
如果我們的pattern本身就是從字符串開頭匹配的話建議使用re.match,因為效率它更快!
url = "https://tongfu.net/home/35.html"
match = re.search(r"home/(d+).html", url)
print(match.group())
print(match.groups())

2.2.3 re.findall
re.findall可以直接返回一個tuple數組,而且可以實現多組匹配。
urls = "https://tongfu.net/home/35.html,"
"https://tongfu.net/home/8.html"
matches = re.findall(r"https://([^/]+)/home/(d+).html", urls)
print(matches)

2.3 替換
2.3.1 re.sub
使用re.sub可以將pattern匹配的字符串片斷替換為我們想要的內容,這裏面還可以將pattern中的匹配組應用到替換內容裏面。
urls = "https://tongfu.net/home/35.html,"
"https://tongfu.net/home/8.html"
matches = re.sub(r"/home/(d+).html", r"/homepage/1.htm", urls)
print(matches)

2.3.2 re.subn
re.subn和re.sub在字符串替換功能上面沒有區別,re.subn比re.sub多了一個替換次數的統計,這個會在返回值裏面體現出來。
urls = "https://tongfu.net/home/35.html,"
"https://tongfu.net/home/8.html"
matches = re.subn(r"/home/(d+).html", r"/homepage/1.htm", urls)
print(matches)

2.4 修飾符
修飾符就是參數flags,用來對pattern進行一個補充。
修飾符 | 描述 |
---|---|
re.I | 忽略大小寫敏感,就是不管大小寫問題,字母對就算匹配了。 |
re.L | 本地化識別匹配。 |
re.M | 多行匹配,默認正則表達式會在遇到換行符後結束匹配,設置這個之後就會一直匹配到末尾。 |
re.S | 使字符「.」匹配換行符,默認字符「.」是不包括換行符的。 |
re.U | 使用Unicode解析字符串,它會影響「w」,「W」,「b」,「B」的作用。 |
re.X | 這個福哥還沒有研究過,官方說法就是可以讓編寫pattern更加簡單。 |
3. 總結
今天福哥帶着童鞋們學習了Python的正則表達式庫re的使用技巧,正則表達式在各種語言的編程時候都是非常重要的庫,使用正則表達式可以讓我們處理字符串變得更加簡單、更加優雅~~
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/284418.html