[英]Regex to capture IP address (S,G) multicast
This regular expression works to capture IP addresses. 此正则表达式用于捕获IP地址。 I need one to capture this format:
我需要一个捕获这种格式:
(1.1.1.1,230.1.1.1) (1.1.1.1,230.1.1.1)
How do I find a proper RegEx? 我如何找到合适的RegEx?
I would like to extract (S,G) as: 我想提取(S,G)为:
1.1.1.1 230.1.1.1 1.1.1.1 230.1.1.1
(...)
match = re.findall(r'^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$' , line)
(...)
You already have a pattern for one IP address. 您已经拥有一个IP地址的模式。 Now that you want to find a parenthesized pair of IP addresses, you could just repeat that pattern, putting
,
in between and \\(
\\)
. 现在,你想找到一个括号对IP地址,你可以只重复模式,把
,
之间和\\(
\\)
If you want to search multiple lines, you may want to add the multiline flag (?m)
. 如果要搜索多行,可能需要添加多行标记
(?m)
。 To actually capture each address en bloc, you have to enclose it as one more group. 要实际捕获整个地址,您必须将其作为另一个组包围。 This would make:
这将使:
match = re.findall(r'(?m)^\((((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))'
+',(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))\)$' , line)
for m in match:
S = m[0]
G = m[4]
print S, G
That is of course ugly. 那当然很难看。 We can improve it in a way by factoring out the repeated parts, eg:
我们可以通过分解重复的部分来改进它,例如:
I = '(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' # pattern for 1 to 255
IP = '(?:' +I+ '\.){3}' +I # pattern for IP address
SG = '(?m)^\((' +IP+ '),(' +IP+ ')\)$' # pattern for (S,G)
match = re.findall(SG, line);
for S, G in match:
print S, G
Here I also inserted ?:
in groups which don't need to be retrieved, so that only the IP addresses remain in the match
. 在这里我还插入了
?:
在不需要检索的组中,以便只有IP地址保留在match
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.