您的位置:首页 > 编程语言 > Python开发

Python中re(正则表达式)学习

2016-10-25 23:27 363 查看


1 re.match:从字符串的开始匹配一个模式,匹配成功返回matchobject。

import
re

text =
"JGood is a handsome boy,
he is cool, clever, and so on..."

m = re.match(r"(\w+)\s",
text)
if m:
print m.group(0),
'\n',
m.group(1)
else:
print
'not match' 

re.match的函数原型为:re.match(pattern, string, flags)

第一个参数是正则表达式,这里为"(\w+)\s",如果匹配成功,则返回一个Match,否则返回一个None;

第二个参数表示要匹配的字符串;

第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
2 re.search:在字符串内查找模式匹配,只到找到第一个匹配然后返回matchobject,如果字符串没有匹配,则返回None。
import
re

text =
"JGood is a handsome boy,
he is cool, clever, and so on..."

m = re.search(r'\shan(ds)ome\s',
text)
if m:
print m.group(0), m.group(1)
else:
print
'not search'

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

3
matchobject.group()包含了所有匹配的内容,等价于matchobject.group(0),此时的0表示所有的匹配。

matchobject.group(n):表示返回正则表达式中的第n个组()匹配的内容,此时n不为0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: