Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex findall works but match does not [duplicate]

Tags:

python

regex

I'm testing this in IPython. The variable t is being set from text in a 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 appears correct to me after reading this documentation. https://docs.python.org/2/howto/regex.html#grouping

I also tested here to verify the regex before trying this in IPython http://regex101.com/r/gG8eQ2/1

What am I missing?

like image 830
Antonios Hadjigeorgalis Avatar asked Nov 29 '14 03:11

Antonios Hadjigeorgalis


1 Answers

SHould be using search, not match. This is what you should have:

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

Match checks only the begining of string. Search goes over whole string.

like image 165
Marcin Avatar answered Oct 14 '22 20:10

Marcin