Python regex string matching?

mowwwalker picture mowwwalker · Oct 1, 2011 · Viewed 43.6k times · Source

I'm having a hell of a time trying to transfer my experience with javascript regex to Python.

I'm just trying to get this to work:

print(re.match('e','test'))

...but it prints None. If I do:

print(re.match('e','est'))

It matches... does it by default match the beginning of the string? When it does match, how do I use the result?

How do I make the first one match? Is there better documentation than the python site offers?

Answer

Oscar Korz picture Oscar Korz · Oct 1, 2011

re.match implicitly adds ^ to the start of your regex. In other words, it only matches at the start of the string.

re.search will retry at all positions.

Generally speaking, I recommend using re.search and adding ^ explicitly when you want it.

http://docs.python.org/library/re.html