Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex string matching?

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?

like image 750
mowwwalker Avatar asked Sep 30 '11 23:09

mowwwalker


People also ask

How do you match a string in Python?

Use the string method startswith() for forward matching, i.e., whether a string starts with the specified string. You can also specify a tuple of strings. True is returned if the string starts with one of the elements of the tuple, and False is returned if the string does not start with any of them.


2 Answers

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

like image 60
Oscar Korz Avatar answered Sep 22 '22 23:09

Oscar Korz


the docs is clear i think.

re.match(pattern, string[, flags])¶

If zero or more characters **at the beginning of string** match the 

regular expression pattern, return a corresponding MatchObject instance. Return None if the string does not match the pattern; note that this is different from a zero-length match.

like image 37
Kent Avatar answered Sep 21 '22 23:09

Kent