ipv4 正则表达式代码在一个元组中给出输出,每个八位字节作为元组中的元素。如何直接打印ip地址?
ipv4 regex code gives output in a tuple with each octet as element in the tuple. How to print the ip address directly?
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')]
使用非捕获组(?: )
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']
此外,由于您有模式 ipdefinition\.
3 次,您可以使用 {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]?)'
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')]
使用非捕获组(?: )
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']
此外,由于您有模式 ipdefinition\.
3 次,您可以使用 {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]?)'