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

Python 正则表达

2017-05-30 20:36 591 查看

1.match和search的区别

def re_method():
# search vs. Match
s = 'abcd'
print(re.search(r'c', s))
print(re.match(r'c', s))
if __name__ == '__main__':
re_method()


返回值为

<_sre.SRE_Match object; span=(2, 3), match='c'>

None


match从字符串的第一个开始进行匹配,可以通过在前面加
.*
的方式找到,其中
.
表示匹配任意字符

re.match(r'.*c', s)


search:搜索字符串任意位置的匹配,可以通过添加
^
^表示某一字符串的开始位置

re.search(r'^c', s)


2.split

分割字符,按照非字母字符

re.split(r'\W+','I love you')


[‘I’, ‘love’, ‘you’]

\W:表示非字母字符,\w:表示字母字符,如果按照\w分割,那么会是另一种结果

3.findall和finditer

findall根据正则表达式从左到右搜索匹配项,返回匹配的字符串列表(跟search是对应的关系,search是只要搜索到匹配的第一个,它就会停下来,findall是会继续往下查找)

re.findall(r'\w+','I love you')


输出
['I', 'love', 'you']


re.findall(r'\d+\.?\d*', 'The beef is $5.6,I like to take 2 piece',)


输出
[5.6 2]


finditer根据正则表达式从左到右搜索匹配项,返回一个迭代器迭代返回MatchObjec

def re_demo():
s = 'The first price is $9.90 and the second price is $100'

i = re.finditer(r'\d+\.?\d*', s)
for m in i:
print(m.group())
re_demo()


4.sub和subn

字符串替换字符串替换

s = 'The first price is $9.90 and the second price is $100'
print(re.sub(r"\$\d+\.?\d*",'<number>',s))


subn和sub一样:返回值多了替换的字符串个数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: