[轉]正則表示式中re.match、re.search、re.findall的用法和區別
阿新 • • 發佈:2021-02-01
技術標籤:技術_程式語言
re.match 用法
re.match語法:re.match(pattern,string,flags=0)
pattern:表示正則表示式
string:要匹配的字元
flags:控制匹配的方式
**re.match匹配方式:**從字元起始位置匹配,若起始位置匹配不成功返回none。即只匹配起始位置
import re string='www.baidu.com' pattern1='www' pattern2='com' m_match1=re.match(pattern1,string) m_match2=re.match(pattern2,string) print(m_match1) print(m_match2)
#結果
<re.Match object; span=(0, 3), match='www'>
None
re.search用法
re.match 只能在起始位置匹配,而re.search可以掃描整個字串並返回第一個成功的匹配
import re
string='www.baidu.com'
pattern='com'
m_match1=re.match(pattern,string)
m_match2=re.search(pattern,string)
print(m_match1)
print(m_match2)
#結果 None <re.Match object; span=(10, 13), match='com'>
re.findall 方法
上述兩個都只能找到一個匹配結果,而findall可以找到所有滿足匹配條件的結果,並以列表的形式返回
import re
string='www.baidu.com,www.runoob.com,www.163.com'
pattern='www'
m_match1=re.match(pattern,string)
m_match2=re.search(pattern,string)
m_match3=re.findall(pattern,string)
print(m_match1)
print(m_match2)
print(m_match3)
#結果 <re.Match object; span=(0, 3), match='www'> <re.Match object; span=(0, 3), match='www'> ['www', 'www', 'www']
三者的區別
#有錯多多指教