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)
import re
class Demo:
def checkIP(self,inputSeq):
patternIP = '^([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])\.([01]?\d\d?|2[0-4]\d|25[0-5])$'
if re.search(patternIP,inputSeq):
return 1
else:
return 0
if __name__ == '__main__':
demo = Demo()
ip = '10.19.10.2'
print demo.checkIP(ip)