RegEx Python无法正常工作

时间:2014-10-13 14:01:02

标签: python regex

我的Reg-Ex模式不起作用,为什么?

string = "../../example/tobematched/nonimportant.html"
pattern = "example\/([a-z]+)\/"
test = re.match(pattern, string)
# None

http://www.regexr.com/39mpu

3 个答案:

答案 0 :(得分:3)

re.match()匹配字符串的开头,您需要使用re.search()查找正则表达式模式生成匹配的第一个位置,并返回相应的MatchObject实例。

>>> import re
>>> s = "../../example/tobematched/nonimportant.html"
>>> re.search(r'example/([a-z]+)/', s).group(1)
'tobematched'

答案 1 :(得分:2)

试试这个。

test = re.search(pattern, string)

匹配从一开始就匹配整个字符串,因此它将给出None作为结果。

test.group()获取结果。

答案 2 :(得分:1)

简短地给你答案:

search⇒在字符串中找到任何地方并返回一个匹配对象。

match⇒在字符串的开头找到一些东西并返回一个匹配对象。

这就是你必须使用

的原因
foo = re.search(pattern, bar)