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)



本博客所有文章采用的授权方式为 自由转载-非商用-非衍生-保持署名 ,转载请务必注明出处,谢谢。
声明:
本博客欢迎转发,但请保留原作者信息!
博客地址:邱文奇(qiuwenqi)的博客;
内容系本人学习、研究和总结,如有雷同,实属荣幸!
阅读次数:

文章评论

comments powered by Disqus


章节列表