java java正则表达式匹配IP地址和端口号作为捕获组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2908740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java regex matching ip address and port number as captured groups
提问by lisak
could please anybody tell me what is wrong with this regexp ?
谁能告诉我这个正则表达式有什么问题?
((?:(?: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]?))\:([0-9]{2,5})
for matching this: assfasfas>192.168.1.1:8080192.168.222.43:8286
匹配这个: assfasfas>192.168.1.1:8080192.168.222.43:8286
I need 192.168.1.1 and 8080 to be captured groups
我需要 192.168.1.1 和 8080 被捕获组
Thank you
谢谢
回答by Tomalak
Unless you really, reallyhave to do IP adress validation, as well, I suggest you simplify the regular expression, because this beast is far too complex for only matching "IP part" and "port part". My suggestion would be
除非你真的,真的必须做 IP 地址验证,我建议你简化正则表达式,因为这个野兽太复杂了,不能只匹配“IP 部分”和“端口部分”。我的建议是
(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}):(\d{1,5})
Groups 1 and 2 will hold IP and port, respectively. And the above is already more complex that it needs to be, IMHO even something as simple as this would be enough:
第 1 组和第 2 组将分别持有 IP 和端口。以上已经比它需要的更复杂了,恕我直言,即使是像这样简单的事情就足够了:
(\d+\.\d+\.\d+\.\d+):(\d+)
Note that double backslashes are are requirement of Java strings, not of regex, so I left them out.
请注意,双反斜杠是 Java 字符串的要求,而不是正则表达式的要求,因此我将它们排除在外。

