1

My Reg-Ex pattern is not working, why?

string = "../../example/tobematched/nonimportant.html"
pattern = "example\/([a-z]+)\/"
test = re.match(pattern, string)
# None

http://www.regexr.com/39mpu

Stephan Kristyn
  • 15,015
  • 14
  • 88
  • 147

3 Answers3

3

re.match() matches from the beginning of the string, you need to use re.search() which looks for the first location where the regular expression pattern produces a match and returns a corresponding MatchObject instance.

>>> import re
>>> s = "../../example/tobematched/nonimportant.html"
>>> re.search(r'example/([a-z]+)/', s).group(1)
'tobematched'
hwnd
  • 69,796
  • 4
  • 95
  • 132
2

Try this.

test = re.search(pattern, string)

Match matches the whole string from the start, so it will give None as the result.

Grab the result from test.group().

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
vks
  • 67,027
  • 10
  • 91
  • 124
1

To give you the answer in short:

search ⇒ finds something anywhere in the string and return a match object.

match ⇒ finds something at the beginning of the string and return a match object.

That is the reason you have to use

foo = re.search(pattern, bar)
BoJack Horseman
  • 4,406
  • 13
  • 38
  • 70