码迷,mamicode.com
首页 > 编程语言 > 详细

python_Note_Preview_02_Regular Expression

时间:2018-07-10 11:18:10      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:file   匹配   type   out   地址   star   tuple   width   imp   

Regular Expression 

技术分享图片

技术分享图片

 

技术分享图片

 

技术分享图片

技术分享图片

技术分享图片

 1 Str = BDefe 129032323 23322d3
 2 
 3 mr = re.search(r[1-9]\d{5}, Str)   #只匹配第一个位置。
 4 if mr:
 5    print(type(mr))
 6    print(mr.groups)
 7    print(mr.groups())
 8    print(mr.group(0))  #获得匹配后的字符串
 9   print(mr.start())   #匹配字符串在原始字符串的开始位置
10   print(mr.end())    #匹配字符串在原始字符串的结束位置
11   print(mr.span())   #返回(.start(), .end())

#Outcome:

技术分享图片

  

技术分享图片

 Example1:

 1 import re
 2 
 3 #匹配3位数字-3到8个数字        \d{3}-\d{3,8}
 4 mr = re.match(r\d{3}-\d{3,8},010-234567)        #\加在‘‘中,\不做转义字符处理。
 5 print(mr.string)
 6 
 7 #分组
 8 m = re.match(r(\d{3})-(\d{3,8})$,010-234567)       #分组时,将第一组用括号括起来。^/$以\d{3-8}为结首/尾。
 9 print(m.groups())
10 print(m.group(0))        #原始字符串
11 print(m.group(1))
12 print(m.group(2))
13 14 #分割字符串
14 >>> p = re.compile(r\d+)          #根据所给出的分隔符进行分割。
15 >>> print(p.split(one1two2three333))
16 [one, two, three, ‘‘]

 #Outcome:

技术分享图片

 Example2: 

 1 >>> t = 2:34:43;343:   er:12:33:32
 2 >>> mr=re.match(r([0-3]?[0-9]+\:[0-5]?[0-9]+\:[0-5]?[0-9]+),t)  #必须从一个字符开始位置起匹配,并只能匹配一个。
 3 >>> type(mr)
 4 <class _sre.SRE_Match>
 5 >>> print(mr.groups)     #不带括号是地址空间。
 6 <built-in method groups of _sre.SRE_Match object at 0x7f87bcd2bf30>
 7 >>> print(mr.groups())
 8 (2:34:43,)
 9 >>> print(mr.group(0))    #原始字符串
10 2:34:43
11 >>> print(mr.group(1))    #第一个元组
12 2:34:43
13 >>> print(mr.group(2))
14 Traceback (most recent call last):
15   File "<stdin>", line 1, in <module>
16 IndexError: no such group
17 >>> print(mr.groups().strip)              #mr.groups()是一个元组。
18 Traceback (most recent call last):
19   File "<stdin>", line 1, in <module>
20 AttributeError: tuple object has no attribute strip
21 >>> mr=re.match(r^([0-3]?[0-9]+)\:([0-5]?[0-9]+)\:([0-5]?[0-9]+),t)  #将每个字段分开,并放入元组中。
22 >>> print(mr.groups())
23 23(2, 34, 43)

技术分享图片

Examples:

 1 >>> t = we2:34:43;343:er:12:22:33
 2 >>> mr=re.match(r([0-3]?[0-9]+\:[0-5]?[0-9]+\:[0-5]?[0-9]+),t)    #match,如果首字母不匹配,就匹配不上了。
 3 >>> print(mr.groups())
 4 Traceback (most recent call last):
 5 "<stdin>", line 1, in <module>
 6 AttributeError: NoneType object has no attribute groups
 7 
 8 >>> m = re.findall(r([0-3]?[0-9]+\:[0-5]?[0-9]+\:[0-5]?[0-9]+),t)  #findall,无需从头匹配,并可以匹配所有。
 9 >>> type(m)
10 <class list>
11 >>> print(m)
12 [2:34:43, 12:22:33]
13 >>> t = 2:34:43;343:er: 12:22:33
14 >>> m = re.findall(r^([0-3]?[0-9]+\:[0-5]?[0-9]+\:[0-5]?[0-9]+),t)  #以数字开头。
15 >>> print(m)
16 [2:34:43]

技术分享图片

技术分享图片

技术分享图片

 

python_Note_Preview_02_Regular Expression

标签:file   匹配   type   out   地址   star   tuple   width   imp   

原文地址:https://www.cnblogs.com/tlfox2006/p/9287291.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!