正则匹配简单运用

2020-02-18  本文已影响0人  下雨天的小蚂蚁

re.match(从头找一个)

re.search(找一个)

re.findall(找所有)

返回一个列表,没有就是空列表

re.findall("\d","chuan1zhi2") >> ["1","2"]

re.sub(替换)

re.sub("\d","_","chuan1zhi2") >> ["chuan_zhi_"]

re.compile(编译,提升匹配速度)

返回一个模型P,具有和re一样的方法,但是传递的参数不同

匹配模式需要传到compile中

p = re.compile("\d",re.S)

p.findall("chuan1zhi2")

假设现在想把字符串 title = u'你好,hello,世界' 中的中文提取出来,可以这么做:

import re

title = u'你好,hello,世界'

pattern = re.compile(ur'[\u4e00-\u9fa5]+')

result = pattern.findall(title)

print result

# 注意点: 中文匹配 需要设置unicode字符才可以匹配

如何非贪婪的去匹配内容?

import re

s = '123xxxxxx456'

result_1 = re.findall('\d+', s)

result_2 = re.findall('\d+?', s)

print(result_1)

print(result_2)

上一篇 下一篇

猜你喜欢

热点阅读