正则 re.match & re.search

re.match函数

re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none。

语法

re.match(pattern, string, flags=0)
  • pattern : 匹配的正则表达式
  • string : 要匹配的字符串。
  • flags : 标志位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。参见 : 正则表达式修饰符 - 可选标志

匹配成功re.match方法返回一个匹配的对象,否则返回None。

我们可以使用group(num) 或 groups() 匹配对象函数来获取匹配表达式。

  • group(num=0) : 匹配的整个表达式的字符串,group() 可以一次输入多个组号,在这种情况下它将返回一个包含那些组所对应值的元组。
  • groups() : 返回一个包含所有小组字符串的元组,从 1 到 所含的小组号。
1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*- 
3  
4 import re
5 print(re.match('www', 'www.runoob.com').span())  # 在起始位置匹配
6 print(re.match('com', 'www.runoob.com'))         # 不在起始位置匹配
案例

输出结果:

(0, 3)
None
 1 #!/usr/bin/python
 2 import re
 3  
 4 line = "Cats are smarter than dogs"
 5  
 6 matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
 7  
 8 if matchObj:
 9    print "matchObj.group() : ", matchObj.group()
10    print "matchObj.group(1) : ", matchObj.group(1)
11    print "matchObj.group(2) : ", matchObj.group(2)
12 else:
13    print "No match!!"
案例

输出结果:

matchObj.group() :  Cats are smarter than dogs
matchObj.group(1) :  Cats
matchObj.group(2) :  smarter

re.search方法

re.search 扫描整个字符串并返回第一个成功的匹配。

语法:

re.search(pattern, string, flags=0)
1 #!/usr/bin/python
2 # -*- coding: UTF-8 -*- 
3  
4 import re
5 print(re.search('www', 'www.runoob.com').span())  # 在起始位置匹配
6 print(re.search('com', 'www.runoob.com').span())         # 不在起始位置匹配
案例

输出结果:

(0, 3)
(11, 14)
 1 #!/usr/bin/python
 2 import re
 3  
 4 line = "Cats are smarter than dogs";
 5  
 6 searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
 7  
 8 if searchObj:
 9    print "searchObj.group() : ", searchObj.group()
10    print "searchObj.group(1) : ", searchObj.group(1)
11    print "searchObj.group(2) : ", searchObj.group(2)
12 else:
13    print "Nothing found!!"
案例

输出结果:

searchObj.group() :  Cats are smarter than dogs
searchObj.group(1) :  Cats
searchObj.group(2) :  smarter

re.match与re.search的区别

re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。

 1 #!/usr/bin/python
 2 import re
 3  
 4 line = "Cats are smarter than dogs";
 5  
 6 matchObj = re.match( r'dogs', line, re.M|re.I)
 7 if matchObj:
 8    print "match --> matchObj.group() : ", matchObj.group()
 9 else:
10    print "No match!!"
11  
12 matchObj = re.search( r'dogs', line, re.M|re.I)
13 if matchObj:
14    print "search --> searchObj.group() : ", matchObj.group()
15 else:
16    print "No match!!"
案例

输出结果:

No match!!
search --> searchObj.group() :  dogs

  

原文地址:https://www.cnblogs.com/shangwei/p/13496655.html