Skip to content Skip to sidebar Skip to footer

Regex: Match Only Once

I've got a string with multiple ip addresses together with some random stuff. For example like this one: 21/Jun/2018:01:15:38 +0000 188.79.169.152 157.52.69.50 443 -

Solution 1:

You can use re.match which matches a ptrn from the beginning of a string So just by adding a .* to the start of your pattern, we can match everything from the beginning of the string to the first ip address

>>> import re
>>> s = "21/Jun/2018:01:15:38 +0000    188.79.169.152    157.52.69.50    443    -    -    GET / 157.52.69.30 157.52.69.10"
>>> 
>>> ptrn = r'.*?([0-9]+(?:\.[0-9]+){3})'
>>> re.match(ptrn, s).groups()[0]
'188.79.169.152'

Post a Comment for "Regex: Match Only Once"