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

stevek-pro
  • 13,672
  • 14
  • 81
  • 134

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
  • 67,942
  • 4
  • 86
  • 123
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
  • 161,711
  • 18
  • 231
  • 272
vks
  • 65,133
  • 10
  • 87
  • 119
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,056
  • 9
  • 34
  • 67