1

I am learning the re module and have a problem understanding re.search and re.match. The documentation gives a good example so I decided to try these out:

>>> import re
>>> pattern = re.compile('\d*')
>>> string = "123"
>>> pattern.match(string)
<_sre.SRE_Match object; span=(0, 3), match='123'>
>>> pattern.search(string)
<_sre.SRE_Match object; span=(0, 3), match='123'>

No surprises here, so I change the string a little:

>>> string = "hello 123"
>>> pattern.match(string)
<_sre.SRE_Match object; span=(0, 0), match=''>
>>> pattern.search(string)
<_sre.SRE_Match object; span=(0, 0), match=''>

Why is nothing found with the last call of search? I would expect it return something like this (a non-empty match object):

<_sre.SRE_Match object; span=(6, 9), match='123'>

What happens during that last call to search? Python 3.4.3

1 Answer 1

3

It's your quantifier! The * quantifier matches ZERO or more of the previous atom (in this case a digit \d). The first match returned is zero quantity at position zero.

I can demonstrate:

>>> import re
>>> pattern = re.compile(r"\d*")
>>> string = "hello 123"
>>> pattern.match(string)
<_sre.SRE_Match object; span=(0, 0), match=''>
>>> pattern.search(string)
<_sre.SRE_Match object; span=(0, 0), match=''>
>>> pattern = re.compile(r"\d+") # + is one or more, not zero or more
>>> pattern.match(string) # no match at start of string
>>> pattern.search(string)
<_sre.SRE_Match object; span=(6, 9), match='123'>
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, I see. However, why does the first search return a successful match and not an empty one then?
Because the first character it sees IS a digit, so it continues to the next one and the next one. When the first character it sees ISN'T a digit, the regex goes "Oh it's okay, the quantifier says I can have nothing here, too. I guess I have nothing!"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.