import re

常用正则表达式符号:

  • '.' 默认匹配除\n之外的任意一个字符,若指定flag DOTALL,则匹配任意字符,包括换行
  • '^' 匹配字符开头,若指定flags MULTILINE,这种也可以匹配上(r"^a","\nabc\neee",flags=re.MULTILINE)
  • '$' 匹配字符结尾,或e.search("foo$","bfoo\nsdfsf",flags=re.MULTILINE).group()也可以
  • '*' 匹配*号前的字符0次或多次,re.findall("ab*","cabb3abcbbac") 结果为['abb', 'ab', 'a']
  • '+' 匹配前一个字符1次或多次,re.findall("ab+","ab+cd+abb+bba") 结果['ab', 'abb']
  • '?' 匹配前一个字符1次或0次
  • '{m}' 匹配前一个字符m次
  • '{n,m}' 匹配前一个字符n到m次,re.findall("ab{1,3}","abb abc abbcbbb") 结果'abb', 'ab', 'abb']
  • '|' 匹配|左或|右的字符,re.search("abc|ABC","ABCBabcCD").group() 结果'ABC'
  • '(...)' 分组匹配,re.search("(abc){2}a(123|456)c", "abcabca456c").group() 结果 abcabca456c
  • '\A' 只从字符开头匹配,re.search("\Aabc","alexabc") 是匹配不到的
  • '\Z' 匹配字符结尾,同$
  • '\d' 匹配数字0-9
  • '\D' 匹配非数字
  • '\w' 匹配[A-Za-z0-9]
  • '\W' 匹配非[A-Za-z0-9]
  • 's' 匹配空白字符、\t、\n、\r , re.search("\s+","ab\tc1\n3").group() 结果 '\t'
  • '(?P<name>...)' 分组匹配
>>> re.search("(?P<province>[0-9]{4})(?P<city>[0-9]{2})(?P<birthday>[0-9]{4})","371481199306143242").groupdict("city") 
{'province': '3714', 'city': '81', 'birthday': '1993'}

常用的匹配语法:

  • re.match 从头开始匹配,只取第一个匹配值
  • re.search 匹配包含
  • re.findall 把所有匹配到的字符放到以列表中并返回
  • re.split 以匹配到的字符当做列表分隔符
  • re.sub(待替换值,取代值,字符串) #匹配字符并替换

注意:
匹配文本中的字符"\",需要4个反斜杠"\\\\"。

范例:

  • 1、匹配IP地址:
re.search("(\d{1,3}\.){3}\d{1,3}","inet 10.1.1.111/24 brd 10.1.1.255 scope global em2
").group()
'10.1.1.111'
  • 2、匹配括号里面没有括号的所有字符串:
re.findall('\([^()]+\)','1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )')
['(-40/5)', '(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )', '(-4*3)', '(16-3*2)']
re.findall('\([^()]+\)','1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )')[0]
['(-40/5)']
 posted on 2017-10-25 10:41  super2feng  阅读(123)  评论(0)    收藏  举报