我的Reg-Ex模式不起作用,为什么?
string = "../../example/tobematched/nonimportant.html"
pattern = "example\/([a-z]+)\/"
test = re.match(pattern, string)
# None
答案 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)