-2
import re

a='my name is xyz. ip address is 192.168.1.0 and my phone number is 1234567890. abc ip address is 192.168.1.2 and phone number is 0987654321. 999.99.99.999'

regex = r'''\b(25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.( 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\b'''
print(re.findall(regex,a))



Output:
[('192', '168', '1', '0'), ('192', '168', '1', '2')]
azro
  • 35,213
  • 7
  • 25
  • 55

1 Answers1

0

Use non-capturing group (?: )

regex = r'''\b(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(?: 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(?: 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.(?: 
            25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\b'''
result = re.findall(regex, a)
print(result) # ['192.168.1.0', '192.168.1.2']

Also as you have the pattern ipdefinition\. 3 time you can use {3}

regex = r'\b(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9][0-9]?)'
azro
  • 35,213
  • 7
  • 25
  • 55