For school I'm supposed to write a Python RE script that extracts IP addresses. The regular expression I'm using seems to work with re.search()
but not with re.findall()
.
exp = "(\d{1,3}\.){3}\d{1,3}" ip = "blah blah 192.168.0.185 blah blah" match = re.search(exp, ip) print match.group()
The match for that is always 192.168.0.185, but its different when I do re.findall()
exp = "(\d{1,3}\.){3}\d{1,3}" ip = "blah blah 192.168.0.185 blah blah" matches = re.findall(exp, ip) print matches[0] 0.
I'm wondering why re.findall()
yields 0. when re.search()
yields 192.168.0.185, since I'm using the same expression for both functions.
And what can I do to make it so re.findall()
will actually follow the expression correctly? Or am I making some kind of mistake?
The re.It searches from start or end of the given string. If we use method findall to search for a pattern in a given string it will return all occurrences of the pattern. While searching a pattern, it is recommended to use re. findall() always, it works like re.search() and re.
match matches the pattern from the start of the string. re. findall however searches for occurrences of the pattern anywhere in the string.
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.
In this article, we will learn how to find all matches to the regular expression in Python. The RE module's re. findall() method scans the regex pattern through the entire target string and returns all the matches that were found in the form of a list.
findall
returns a list of matches, and from the documentation:
If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.
So, your previous expression had one group that matched 3 times in the string where the last match was 0.
To fix your problem use: exp = "(?:\d{1,3}\.){3}\d{1,3}"
; by using the non-grouping version, there is no returned groups so the match is returned in both cases.
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