【问题标题】:Python regex findall works but match does not [duplicate]Python 正则表达式 findall 有效,但匹配不 [重复]
【发布时间】: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

我错过了什么?

【问题讨论】:

标签: python regex


【解决方案1】:

应该使用search,不匹配。这是你应该拥有的:

p = re.compile(r)
m = p.search(t)
if m: print(m.group(1)) # gives: B003T0G9GM

Match 只检查字符串的开头。搜索整个字符串。

【讨论】:

    猜你喜欢
    • 2017-03-01
    • 2012-10-31
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多