Python正规则表达式

python中主要使用re模块进行正则操作
图片描述
这是python正则基本元字符
. 如 r.d 会匹配 red、r d等。不会匹配read;
* 如 r*ed 会匹配 ed、rred、rrrred、red等。;
+ 如 r+ed 会匹配 rred、rrred等。不会匹配ed;
| 如 abc|acd。会匹配abc或者acd;
[] 匹配[]中任一字符 如r[bc]d,匹配rbd或者rcd;
贪婪与非贪婪模式可以看一下
^与[Math Processing Error]只会匹配第三行的
如果嫌转义符麻烦可以使用r 如re.match(r’hello’,str)

元字符可以结合使用
.*匹配任意个字符 r.*d可以匹配rd red read等
.+匹配一个或多个 r.+d匹配 red read等
.?匹配0个或一个

例子匹配号码
如13134567890
13[0-9][0-9]{8}或者13[0-9]{9}

匹配网址
http://www|www).[a-zA-Z0-9]*.{a-z}{2,3}
or r’(http://www|www).[a-zA-Z0-9]*.{a-z}{2,3}’

主要使用函数 re.match()
re.findall()
re.search()
re.sub()
re.subn()
re.spilt()

match与search差不多match是从str第一个开始匹配 search则是搜索整个str
例如 s=’hello world ichunqiu’
re.match(‘world’,s)与·re.search(‘world’,s)结果不一样
re.match(‘WORLD’,s,re.I)可以忽略大小写(re.I)

re.sub()与re.subn()区别
re.sub(‘world’,’beauty’,s)
‘hello beauty ichunqiu’

re.subn(‘hello’,’beauty’,s)
(‘beauty beauty ichunqiu’,1(替换次数))

相关链接:http://bbs.ichunqiu.com/thread-9082-1-1.html?from=csdnJG