Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

python 模块-re

$
0
0

如果想匹配元字符本身或者正则中的一些特殊字符,使用 \ 转义。例如匹配 * 这个字符则使用 \* ,匹配 \ 这个字符,使用 \\ 。

需要转义的字符: $ , ( , ) , * , + , . , [ , ] , ? , \ , ^ , { , } , | 为了避免过多\的使用,python提供了原生字符的方法,也就是在字符串前面加上一个“r”,代表此字符串中的“\”可直接用于正则表达式,而不用再次转义。因此,请养成在python的正则表达式字符串的前面添加一个“r“的好习惯。 二、re模块的方法

1、match

re.match(' 规则','字符串 ') 从字符串的开头进行匹配,匹配单个。

2、search

re.search(' ',' ') 在字符串中进行匹配,并返回第一个匹配到的值。

3、findall

re.findall('','') 在字符串中进行匹配,并以列表的形式 返回所有满足 的值。

>>> re.findall('\d+','dsg2335dhreh54623grh46fdh57')

['2335', '54623', '46', '57']

4、group,groups

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()

5、sub

sub(pattern, repl, string, count=0, flags=0)用于替换匹配到的字符串。

>>> 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

Viewing all articles
Browse latest Browse all 9596

Trending Articles