python-正則表達式2-常用方法:match()、search()、findall()、sub()、compile()

常用方法:match()、search()、findall()、sub()、compile()

match():從字符串的起始位置匹配。若匹配,返回匹配成功的結果;若不匹配,返回None。因爲需考慮開頭的內容,適合用來檢測某個字符串是否符合某個正則表達式的規則。
search():從字符串的起始位置依次掃描字符串,直到找到第一個符合規則的字符串,返回匹配內容。若掃描完還沒有找到,則返回None。
findall():從字符串的起始位置依次掃描字符串,找到所有符合規則的字符串,以list類型方式返回匹配內容。
sub():修改字符串。可先使用sub()方法,再使用findall()方法,簡化findall()提取信息的過程。
compile():將正則表達式編譯成正則表達式對象,以便於在後面的匹配中複用。

match()方法
re.match(pattern=, string=, flags=),pattern爲正則表達式,必填;string爲目標字符串,必填;flags爲修飾符,選填。

# 舉慄:有一學生信息的字符串。校驗字符串開頭是否是名字,且名字佔4個字符。
import re
stu = 'name is Jack,age is 25,sex is male,job is tester.'
stu_start = re.match('name is \w{4},', stu)
print(stu_start.group())

search()方法
re.search(pattern=, string=, flags=),pattern爲正則表達式,必填;string爲目標字符串,必填;flags爲修飾符,選填。

# 舉慄:有一學生信息的字符串。校驗字符串是否包含年齡信息,且年齡佔2個字符。
import re
stu = 'name is Jack,age is 25,sex is male,job is tester.'
stu_age = re.search('age is \d{2},', stu)
print(stu_age.group())

正則表達式開頭加“^”,表示匹配字符串的開頭,因此該符號與search()方法結合使用,等價於match()方法。

# 舉慄:有一學生信息的字符串。校驗字符串開頭是否是名字,且名字佔4個字符。
import re
stu = 'name is Jack,age is 25,sex is male,job is tester.'

# 使用search()方法
stu_start_1 = re.search('^name is \w{4},', stu)
print(stu_start_1.group())

# 使用match()方法
stu_start_2 = re.match('name is \w{4},', stu)
print(stu_start_2.group())

findall()方法
re.findall(pattern=, string=, flags=),pattern爲正則表達式,必填;string爲目標字符串,必填;flags爲修飾符,選填。

# 舉慄:有一包含多個學生信息的字符串,信息內容有姓名、年齡。現在要找出所有學生的姓名。
import re
stu = 'name is Jack,age is 25.name is Jane,age is 26.name is Tony,age is 27.'
stu_names = re.findall('name is \w{4}', stu)
print(stu_names)

sub()方法
re.sub(pattern=, repl=, string=, count=, flags=),pattern爲正則表達式,必填;repl爲修改的內容,必填;string爲目標字符串,必填;count爲??, 選填;flags爲修飾符,選填。

# 舉慄:有學生信息,信息內容有姓名、年齡。現在要修改信息內容,去掉年齡信息。
import re
stu1 = 'name is Jack,age is 25'
# 修改內容。
stu1_new = re.sub('age is \d{2}', '', stu1)
print(stu1_new)

compile()方法
re.compile(pattern=, flags=),pattern爲正則表達式,必填;flags爲修飾符,選填。

# 舉慄:有三個學生信息,信息內容有姓名、年齡。現在要修改信息內容,去掉年齡信息。
import re
stu1 = 'name is Jack,age is 25'
stu2 = 'name is Jane,age is 26'
stu3 = 'name is Tony,age is 27'

# 創建一個正則表達式對象。
pattern = re.compile('age is \d{2}')
# 修改內容。
stu1_1 = re.sub(pattern, '', stu1)
stu2_1 = re.sub(pattern, '', stu2)
stu3_1 = re.sub(pattern, '', stu3)
print(stu1_1)
print(stu2_1)
print(stu3_1)

# 若直接使用正則表達式,則如下:
stu1_2 = re.sub('age is \d{2}', '', stu1)
stu2_2 = re.sub('age is \d{2}', '', stu2)
stu3_2 = re.sub('age is \d{2}', '', stu3)
print(stu1_2)
print(stu2_2)
print(stu3_2)

通過對比可發現,
使用正則表達式對象時,只需要寫一個正則表達式對象,然後可以重複使用;需要修改正則表達式時,只需要修改一個正則表達式對象。
而直接使用正則表達式時,則有多少個學生,就需要寫多少個表達式;需要修改正則表達式時,也每個都要修改一遍。

本文來自:https://blog.csdn.net/yisumi
end…

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