想要在python中使用正则表达式,就需要先导入re模块,正则表达式是一个强大的功能,可以为我们节省很多工作量。
如果想匹配元字符本身或者正则中的一些特殊字符,使用\
转义。例如匹配*
这个字符则使用\*
,匹配\
这个字符,使用\\
。
需要转义的字符:$
, (
, )
, *
, +
, .
, [
, ]
, ?
, \
, ^
, {
, }
, |
为了避免过多\的使用,python提供了原生字符的方法,也就是在字符串前面加上一个“r”,代表此字符串中的“\”可直接用于正则表达式,而不用再次转义。因此,请养成在python的正则表达式字符串的前面添加一个“r“的好习惯。
1、match
a = "123abc456" print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group() print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(0) print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(1) print re.search("([0-9]*)([a-z]*)([0-9]*)", a).group(2) print re.search("([0-9]*)([a-z]*)([0-9]*)", a).groups()
>>> import re >>> a = ‘sfgwg323dgw13‘ >>> b = re.sub(r‘\d+‘,‘111‘,a) >>> b ‘sfgwg111dgw111‘
6、split(pattern, string, maxsplit=0, flags=0) 根据指定匹配进行分组
content = "‘1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )‘" new_content = re.split(‘\*‘, content) # new_content = re.split(‘\*‘, content, 1) print new_content
content = "‘1 - 2 * ((60-30+1*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2) )‘" new_content = re.split(‘[\+\-\*\/]+‘, content) # new_content = re.split(‘\*‘, content, 1) print new_content
inpp = ‘1-2*((60-30 +(-40-5)*(9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2))‘ inpp = re.sub(‘\s*‘,‘‘,inpp) new_content = re.split(‘\(([\+\-\*\/]?\d+[\+\-\*\/]?\d+){1}\)‘, inpp, 1) print new_content
原文:http://www.cnblogs.com/ernest-zhang/p/5634078.html