正則表達(dá)式使用步驟
1. 用import re導(dǎo)入正則表達(dá)式
2. 用re.compile()函數(shù)創(chuàng)建一個(gè)Regex對(duì)象
3. 向Regex對(duì)象的search()方法傳入想查找的字符串,它返回一個(gè)Match對(duì)象
4. 調(diào)用Match對(duì)象的group方法,返回實(shí)際匹配文本的字符串
import re
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
mo = phoneNumRegex.search('My number is 415-332-9870')
print('Phone number found: '+ mo.group())
創(chuàng)建分組
添加括號(hào)將在正則表達(dá)式中創(chuàng)建“分組”:(\d\d\d)-(\d\d\d-\d\d\d\d)
然后可以使用group()匹配對(duì)象方法,從一個(gè)分組獲取匹配的文本。向group方法傳入0或不傳入?yún)?shù),將返回整個(gè)文本,向group方法傳入整數(shù)1或2,就可以取得匹配文本的不同部分。
group1 = mo.group(1)
group2 = mo.group(2)
print(group1)
print(group2)
一次獲得所有的分組,使用groups()方法:
areaCode, mainNumber = mo.groups()
print(areaCode)
print(mainNumber)
不同特殊字符的用法:
“|”希望匹配許多表達(dá)式中的一個(gè)時(shí),
正則表達(dá)式r'Batman|Tina Fey'將匹配Batman或者Tina Fey, 如果它們都出現(xiàn)在被查找的字符串中,第一次出現(xiàn)的匹配文本將作為Match對(duì)象返回。
heroRegex = re.compile(r'Batman|Tina Fey')
mo1 = heroRegex.search("Batman and Tina Fey")
print(mo1.group()) ?# 返回Batman
mo2 = heroRegex.search("Tina Fey and Batman")
print(mo2.group()) ?# 返回Tina Fey
"|"中的括號(hào)分組使用
batRegex = re.compile(r'Bat(man|mobile|copter|bat)')
mo = batRegex.search("Batmobile lost a wheel.")
print(mo.group(1)) ?# 匹配括號(hào)中出現(xiàn)的第一個(gè)字符
print(mo.group()) # 匹配整個(gè)對(duì)應(yīng)字符
"?"實(shí)現(xiàn)可選匹配,匹配這個(gè)問號(hào)之前的分組零次或一次
batRegex = re.compile(r'Bat(wo)?man')
mo1 = batRegex.search("The adventures of Batman.")
mo2 = batRegex.search("The adventures of Batwoman.")
print(mo1.group()) ?# 返回Batman
print(mo2.group()) ?# 返回Batwoman
"*"實(shí)現(xiàn)匹配零次或多次
batRegex = re.compile(r'Bat(wo)*man')
mo1 = batRegex.search("The adventures of Batman.")
mo2 = batRegex.search("The adventures of Batwowowowoman.")
mo3 = batRegex.search("The adventures of Batwoman.")
print(mo1.group())
print(mo2.group())
print(mo3.group())
“+”匹配一次或多次
batRegex = re.compile(r'Bat(wo)+man')
mo1 = batRegex.search("The adventures of Batman.")
mo2 = batRegex.search("The adventures of Batwowowowoman.")
mo3 = batRegex.search("The adventures of Batwoman.")
print(mo1 == None) ?# 返回True 沒有匹配結(jié)果
print(mo2.group())
print(mo3.group())
“{n}”匹配出現(xiàn)的次數(shù)
haRegex = re.compile(r'(Ha){3}')
mo1 = haRegex.search('HaHaHa')
print(mo1.group())
mo2 = haRegex.search('Ha')
print(mo2 == None)
貪心和非貪心匹配
在次數(shù)后面加上?表示非貪心匹配,如{3,5}?則只匹配3次。
greedyHaRegex = re.compile(r'(Ha){3,5}')
nongreedyHaRegex = re.compile(r'(Ha){3,5}?')
mo1 = greedyHaRegex.search('HaHaHaHaHa')
print(mo1.group())
mo2 = nongreedyHaRegex.search('HaHaHaHaHa')
print(mo2.group())
findall()方法
1. 如果調(diào)用在一個(gè)沒有分組的正則表達(dá)式上,findall()將返回一個(gè)匹配字符串的列表
2. 如果調(diào)用在一個(gè)有分組的正則表達(dá)式上,findall()將返回一個(gè)字符串的元組列表
phoneNumRegex = re.compile(r'\d\d\d-\d\d\d-\d\d\d\d')
number_str = "Cell:415-555-9999 Work:212-555-0000"
mo = phoneNumRegex.findall(number_str)
print(mo)
phoneNumRegex = re.compile(r'(\d\d\d)-(\d\d\d)-(\d\d\d\d)')
number_str = "Cell:415-555-9999 Work:212-555-0000"
mo1 = phoneNumRegex.findall(number_str)
print(mo1)
開始和結(jié)束匹配
# ^ and $
beginsWithHello = re.compile(r'^Hello')
mo = beginsWithHello.search("Hello World")
print(mo.group())
endWithNumber = re.compile(r'\d$')
mo1 = endWithNumber.search("Your age is 23")
print(mo1.group())
.*匹配所有字符
nameRegex = re.compile(r'First Name: (.*) Last Name: (.*)')
mo2 = nameRegex.search("First Name: Al Last Name: Sweigart")
print(mo2.group())
re.I傳入compile第二個(gè)參數(shù),忽略大小寫
robocop = re.compile(r'robocop',re.I)
mo3 = robocop.search('RoBocop is part man, part machine, all cop')
mo4 = robocop.search('ROBOCOP is part man, part machine')
print(mo3.group())
print(mo4.group())
sub()方法
namesRegex = re.compile(r'Agent \w+')
mo5 = namesRegex.sub('CENSORED','Agent Alice gave the secret to Agent Bob.')
print(mo5)
agentNamesRegex = re.compile(r'Agent (\w)(\w*)')
mo6 = agentNamesRegex.sub(r'*\2','Agent Alice told Agent Carol that Agent Eve knew Agent Bob was a double agent.')
print(mo6)