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')]
Asked
Active
Viewed 57 times
-2

azro
- 53,056
- 7
- 34
- 70

Ravi Pande
- 1
- 1
1 Answers
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
- 53,056
- 7
- 34
- 70