Python regex findall works but no match

I am testing this in IPython. The variable is t

set from the text in the dictionary and returns:

u'http://www.amazon.com/dp/B003T0G9GM/ref=wl_it_dp_v_nS_ttl/177-5611794-0982247?_encoding=UTF8&colid=SBGZJRGMR8TA&coliid=I205LCXDIRSLL3'

      

using this code:

r = r'amazon\.com/dp/(\w{10})' 
m = re.findall(r,t)

      

matches correctly and m

returns[u'B003T0G9GM']

Using this code,

p = re.compile(r)
m = p.match(t)

      

m

returns None

This looks correct to me after reading this documentation. https://docs.python.org/2/howto/regex.html#grouping

I also checked here to check the regex before trying it in IPython http://regex101.com/r/gG8eQ2/1

What am I missing?

+3


source to share


1 answer


Search should be used , not match. This is what you need:

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

      



The match only checks the beginning of the string. The search goes through the whole line.

+4


source







All Articles