tags:

views:

140

answers:

3

I have recently been jumping into understanding regex with python.

I have been looking at the api; I can't seem to understand the difference between:

re.match vs. re.search

when is it best to use each of these? pros? cons?

Please and thank you.

+7  A: 

re.match() matches only from the beginning of the string. A common gotcha. See the documentation.

chryss
Exactly. Trivial (too trivial, e.g. doesn't account for MULTILINE mode) implementation: re.match = lambda pattern, string, flags = 0: re.search('^'+pattern, string, flags)
delnan
@delnan: That would be `\A`. But actually `match` is more primitive than `search`.
KennyTM
+7  A: 

From Matching vs. Searching:

match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string.

>>> re.match("c", "abcdef")  # No match
>>> re.search("c", "abcdef") # Match
<_sre.SRE_Match object at ...>
Jon-Eric
A: 

I just learned you can also search for substrings this way:

if 'c' in 'abcdef'

True

monstru0