Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why re.search(r'(ab*)','aaAaABBbbb',re.I) in python gives result 'a' instead of 'ABBbbb' though 're.I' is used?

Tags:

python

regex

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
like image 965
Sandeep Samal Avatar asked Dec 06 '15 11:12

Sandeep Samal


People also ask

Is there any difference between re match () and re search () in the Python re module?

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.

What is the return value of re search in Python?

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.

How do you're match in Python?

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.


2 Answers

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.

like image 161
Tom Zych Avatar answered Oct 28 '22 02:10

Tom Zych


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.

like image 35
Maroun Avatar answered Oct 28 '22 04:10

Maroun