python基础-re正则

一:什么是正则?

 正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。

  (在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。

   .代表任意字符:print(re.findall('h...o$','egon 123 + _ - *hello'))

  ?代表?左边的字符出现0次或者1 :print(re.findall('ab?','a ab abb abbbb a1b'))

   *代表*号左边的字符出现0次或者无穷次:print(re.findall('ab*','a ab abb abbbb a1b'))

   +代表+号左边的字符出现1次或者无穷次:print(re.findall('ab+','a ab abb abbbb a1b'))

   {m,n}代表左边的字符出现m次到n次::print(re.findall('ab{0,1}','a ab abb abbbb a1b'))无穷次可不写n

   .*代表贪婪匹配:print(re.findall('a.*b','xxxxxxy123a123b456b'))

   .*?代表非贪婪匹配:print(re.findall('a.*?b','xxxxxxy123a123b456b'))

   |代表或者:#默认留组中的内容 print(re.findall('compan(y|iess)','Too many companiess have gone bankrupt, and the next one is my company'))

                     #:?匹配成功后不留组中取到的内容留取到的全部内容print(re.findall('compan(?:y|iess)','Too many companiess have gone bankrupt, and the next one is my company'))

   []代表取中括号内任意的一个:print(re.findall('a[a-z]b','axb azb aAb alb a-b a+b'))中括号中开头加^表示取反

二:re模块的其他方法:

     re.search:只匹配成功一次就返回print(re.search('a[^-+*/]b','axb azb aAb a1b a-b a+b').group())

     re.match:从开头取,且只匹配一次,取不到返回None:print(re.match('a[0-9]b','axb azb aAb a1b a-b a+b'))

     re.split:实现切割:print(re.split(':','root:x:0:0::/root:/bin/bash',maxsplit=1))

     re.sub代表替换:print(re.sub('root','admin','root:x:0:0::/root:/bin/bash',1))

     re.compile:obj=re.compile('a\d{2}b') print(obj.findall('a12b a123b a12345b abbb'))

posted @ 2019-12-19 11:10  birdfish  阅读(550)  评论(0编辑  收藏  举报