Python值正则表达式(RE)

要想在Python中使用正则表达式,首先要引入模块: import re 

 


.    匹配任意一个

+     匹配至少一个

*    匹配0个至多个

?    1个或0个(可有可无)

-    表范围

\    转义

^     在首

$    在尾


 

例:将‘branches’编译成对象s,不区分大小写。要特别注意 re.I 这个属性

1 >>> import re
2 >>> s = re.compile(r'branches',re.I)
3 >>> s.findall('Branches')
4 ['Branches']
5 >>> s.findall('BraNches')
6 ['BraNches']
7 >>> 

 

 

1 >>> s
2 '123+456-789*000'
3 >>> re.split(r'[\+\-\*]',s)
4 ['123', '456', '789', '000']
5 >>> 

要特别注意 S、 I、 M、 V 这几个

 1   >>> s="""
 2   ... hello csvt
 3   ... csvt hello
 4   ... hello csvt hello
 5   ... csvt hehe
 6   ... """
 7  >>> r = r'^csvt'
 8  >>> re.findall(r,s)
 9  []
10  >>> s
11  '\nhello csvt\ncsvt hello\nhello csvt hello\ncsvt hehe\n'
12  >>> re.findall(r,s,re.M)
13  ['csvt', 'csvt']
14  >>> 

 

 1 >>> tel = r"""
 2 ... \d{3,4}
 3 ... -?
 4 ... \d{8}
 5 ... """
 6 >>> re.findall(tel, '010-12345678')
 7 []
 8 >>> 
 9 >>> re.findall(tel, '010-12345678', re.X)
10 ['010-12345678']
11 >>> 

 匹配email:

 1 >>> email = r"\w{3}@\w+(\.com|\.cn)"
 2 >>> re.match(email, 'xxx@haha.com')
 3 <_sre.SRE_Match object at 0xb76c4420>
 4 >>> re.match(email, 'xxx@haha.cn')
 5 <_sre.SRE_Match object at 0xb768e4a0>
 6 >>> re.match(email, 'xxx@haha.org')
 7 >>> 
 8 >>> re.findall(email, 'zzz@csvt.com')
 9 ['.com']
10 >>> 

 

posted on 2017-06-11 12:20  枝桠  阅读(385)  评论(0编辑  收藏  举报

导航