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 <
You're only capturing the 0 in that regex, as it'll be the last one that's caught.
Change the expression to capture the entire IP, and the repeated part to be a non-capturing group:
In [2]: ip = "blah blah 192.168.0.185 blah blah"
In [3]: exp = "((?:\d{1,3}\.){3}\d{1,3})"
In [4]: m = re.findall(exp, ip)
In [5]: m
Out[5]: ['192.168.0.185']
In [6]:
And if it helps to explain the regex:
In [6]: re.compile(exp, re.DEBUG)
subpattern 1
max_repeat 3 3
subpattern None
max_repeat 1 3
in
category category_digit
literal 46
max_repeat 1 3
in
category category_digit
This explains the subpatterns. Subpattern 1 is what gets captured by findall.
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.