正则表达式使用单个字符串来描述、匹配一系列符合某个句法规则的字符串。在很多文本编辑器里,正则表达式通常被用来检索、替换那些符合某个模式的文本。许多程序设计语言都支持利用正则表达式引擎。
正则表达式(RE)是一种小型的、高度专业化的编程语言,在(python中)它内嵌在python中,并通过re模块实现。
可以为想要匹配的相应字符串集指定规则。该字符串集可能包含英文语句、e-mail地址、命令或任何你想搞定的东西。
字符匹配:
——普通字符:大多数字母和字符一般都会和自身匹配,如正则表达式test会和字符串“test”完全匹配。
——元字符:. ^ * + ? {} [] \ | ()
[]常用来指定一个字符集:[abc];[a-z];元字符在字符集中不起作用:[akm$];补集匹配不再区间范围内的字符:[^5]
^匹配行首
$匹配行尾,行尾被定义为要么是字符串尾,要么是一个换行字符后面的任何位置。
>>>import re
>>>s=r'abc' #定义规则
>>>re.findall(s,"aaaaaaaaaa")
[]
>>>re.findall(s,"aabcaaaaaaaaaaa")
['abc']
>>>re.findall(s,"abcaaaaaaaaaaaabcaaa")
['abc','abc']
字符集
>>>import re
>>>st='top tip tap twp trp tep'
>>>res=r't[ioe]p'
>>>re.findall(res,st)
['top','tip','tep']
>>>res=r't[^ioe]p' #补集
>>>re.findall(res,st)
['tap','twp','trp']
匹配行首和行末字符串:
>>>s='hello world,hello boy'
>>>r=r'hello'
>>>re.findall(r,s)
['hello','hello']
>>>r=r'^hello'#匹配行首的字符串,看是否是hello开头
>>>re.findall(r,s)
['hello']
>>>s='world,hello boy'
>>>re.findall(r,s)
[] #行首不是hello,返回空列表
>>>r=r'boy$'#匹配行末字符串,看是否是boy结尾
>>>re.findall(r,s)
['boy']
>>>s='hello boy world'
>>>r=r'boy$'
>>>re.findall(r,s)
[] #行末不是boy,返回空列表
元字符在字符集中不起作用:
>>>r=r't[abc$]'#匹配以ta、tb、tc,t$结尾字符串,即元符号在字符集中不起作用
>>>re.findall(r,'ta')
>>>['ta']
>>>re.findall(r,'tb')
['tb']
>>>re.findall(r,'tax')
['ta']
>>>re.findall(r,'t$')#把$符号当做一个普通字符对待
['t$']
>>>r='t[abc^]'#把^符号当做一个普通字符对待
>>>re.findall(r,'t^')
['t^']
>>>r=r'x[0123456789]x'
>>>re.findall(r,'x1x x2x x9x')
['x1x','x2x','x9x']
>>>r=r'x[0-9]x'
>re.findall(r,'x1x x2x x9x')
['x1x','x2x','x9x']
>>>r=r'x[a-zA-Z0-9]'
>>>re.findall(r,'x1x x2x x9x')
['x1x','x2x','x9x']