四时宝库

程序员的知识宝库

Python正则表达式match函数,你学会了吗?

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

使用Python的‘r’前缀,就不用考虑转义的问题了

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

测试用例

#!/usr/bin/python

import re

line = "Cats are smarter than dogs"

matchObj = re.match( r'(.*) are (.*?) (.*)', line, re.M|re.I)

if matchObj:

print "matchObj.group() : ", matchObj.group()

print "matchObj.group(1) : ", matchObj.group(1)

print "matchObj.group(2) : ", matchObj.group(2)

print "matchObj.group(3) : ", matchObj.group(3)

else:

print "No match!!"

python test.py

matchObj.group() : Cats are smarter than dogs

matchObj.group(1) : Cats

matchObj.group(2) : smarter

matchObj.group(3) : than dogs

变形一

matchObj = re.match( r'(.*) are (.*) .*', line, re.M|re.I)

python test.py

matchObj.group() : Cats are smarter than dogs

matchObj.group(1) : Cats

matchObj.group(2) : smarter than

matchObj.group(3) :

Traceback (most recent call last):

File "test.py", line 12, in <module>

print "matchObj.group(3) : ", matchObj.group(3)

IndexError: no such group

你在正则表达式内所看到的,通过括号括起来的group,编号分别对应着1,2,3,少了个()导致数组越界报错

变形二

matchObj = re.match( r'(.*) are (.*) (.*)', line, re.M|re.I)

python test.py

matchObj.group() : Cats are smarter than dogs

matchObj.group(1) : Cats

matchObj.group(2) : smarter than

matchObj.group(3) : dogs

. 代表任意字符

* 匹配前面的字符或者子表达式0次或多次,因为没有?,所以group2会匹配多次

变形三

matchObj = re.match( r'(.*) (.*?) (.*)', line, re.M|re.I)

python test.py

matchObj.group() : Cats are smarter than dogs

matchObj.group(1) : Cats are smarter

matchObj.group(2) : than

matchObj.group(3) : dogs

. 代表任意字符

* 匹配前面的字符或者子表达式0次或多次

*? 惰性匹配上一个

变形四

matchObj = re.match( r'(.*?) (.*?) (.*)', line, re.M|re.I)

python test.py

matchObj.group() : Cats are smarter than dogs

matchObj.group(1) : Cats

matchObj.group(2) : are

matchObj.group(3) : smarter than dogs

变形五

matchObj = re.match( r'(.*) (.*) (.*)', line, re.M|re.I)

python test.py

matchObj.group() : Cats are smarter than dogs

matchObj.group(1) : Cats are smarter

matchObj.group(2) : than

matchObj.group(3) : dogs

变形六

matchObj = re.match( r'(.*)(.*) (.*)', line, re.M|re.I)

python test.py

matchObj.group() : Cats are smarter than dogs

matchObj.group(1) : Cats are smarter than

matchObj.group(2) :

matchObj.group(3) : dogs

因(.*)(.*)间没有空格,所以group2匹配为空

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言
    友情链接