Python正则表达式
发布于 2018-03-06 · 本文总共 932 字 · 阅读大约需要
3 分钟
正则表达式
匹配
最短匹配
>>> text = "this is a test text:'abc' text2:'def'"
>>>
>>> pat = re.compile(r"\'(.*)\'")
>>>
>>> pat.findall(text)
["abc' text2:'def"]
>>>
>>> pat = re.compile(r"\'(.*?)\'")
>>>
>>> pat.findall(text)
['abc', 'def']
换行符处理
>>> pat = re.compile(r"\'(.*?)\'", re.DOTALL)
替换
>>> text = "Mon/Jun/15 01:09:22 2020"
>>>
>>> re.sub(r'/(\d+)', r'-\1', text)
'Mon/Jun-15 01:09:22 2020'
>>>
>>> pat = re.compile(r'/(\d+)')
>>>
>>> pat.sub(r'-\1', text)
'Mon/Jun-15 01:09:22 2020'
>>> pat.subn(r'-\1', text)
('Mon/Jun-15 01:09:22 2020', 1)