In python, re.search()
checks for a match anywhere in the string (this is what Perl does by default).
So why don't we get output as 'ABBbbb' in Ex(1) as we found in Ex(2) and Ex(3) below.
Ex(1)
>>> s=re.search(r'(ab*)','aaAaABBbbb',re.I)
>>> print s.group()
a
Ex(2)
>>> s=re.search(r'(ab.*)','aaAaABBbbb',re.I)
>>> print s.group()
ABBbbb
Ex(3)
>>> s=re.search(r'(ab+)','aaAaABBbbb',re.I)
>>> print s.group()
ABBbbb
There is a difference between the use of both functions. Both return the first match of a substring found in the string, but re. match() searches only from the beginning of the string and return match object if found.
The re.search() function will search the regular expression pattern and return the first occurrence. Unlike Python re. match(), it will check all lines of the input string. If the pattern is found, the match object will be returned, otherwise “null” is returned.
match() function of re in Python will search the regular expression pattern and return the first occurrence. The Python RegEx Match method checks for a match only at the beginning of the string. So, if a match is found in the first line, it returns the match object.
Example 1 is searching for a
followed by zero or more b
, ignoring case. This matches right at the beginning of the string. The regex engine will see that match and use it. It won't look for any other matches.
Example 2 is searching for ab
followed by as much of the string as it can eat. Example 3 is searching for a
following by at least one b
. The difference is that each of these needs at least one b
, while Example 1 does not.
search
:
checks for a match anywhere in the string (this is what Perl does by default).
re.search(r'(ab*)', 'aaAaABBbbb', re.I)
This will try to match a
(case ignored) followed by zero or more b
. It find that match in the first a
, since it's followed by zero b
, and it returned it.
re.search(r'(ab.*)', 'aaAaABBbbb', re.I)
This one will try to match a
, followed by b
and then with anything (.*
is greedy). It matches ABBbbb
because it's the first sequence that matches the regex.
re.search(r'(ab+)', 'aaAaABBbbb', re.I)
Finally, this will match a
, followed by at least one b
(again, case ignored). That first match is ABBbbb
, and it's returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With