【发布时间】:2015-01-27 16:48:18
【问题描述】:
我正在 IPython 中对此进行测试。变量t 是从字典中的文本设置并返回:
u'http://www.amazon.com/dp/B003T0G9GM/ref=wl_it_dp_v_nS_ttl/177-5611794-0982247?_encoding=UTF8&colid=SBGZJRGMR8TA&coliid=I205LCXDIRSLL3'
使用此代码:
r = r'amazon\.com/dp/(\w{10})'
m = re.findall(r,t)
匹配正确,m 返回[u'B003T0G9GM']
使用此代码,
p = re.compile(r)
m = p.match(t)
m 返回None
阅读本文档后,这对我来说似乎是正确的。 https://docs.python.org/2/howto/regex.html#grouping
在 IPython 中尝试之前,我还在这里进行了测试以验证正则表达式 http://regex101.com/r/gG8eQ2/1
我错过了什么?
【问题讨论】:
-
match从字符串的开头匹配,您可能需要search代替。见What is the difference between Python's re.search and re.match?。