Simple Java regex to extract IP address and port from enclosing string

橙三吉。 提交于 2019-12-14 02:36:34

问题


Consider a pair of IPv4 or IPv6 address and port, separated by either / or :, e.g.

10.10.10.10:1234

The port is optional, so strings like

10.10.10.10/
10.10.10.10:
10.10.10.10

are also valid. The address/port pair may be followed by space or comma characters and it is part of a much longer enclosing string.

What would be a very simple regex to extract the 2 values in separate fields from the enclosing string (without using String manipulation functions)?

For example, an expression like

(?<address>[^\s,]+[^\s,:\.])((/|:)(?<port>\d*))?

extracts both address and port in the same string.

The goal here is to achieve extraction with the simplest possible regex, even if it is not 100% accurate (i.e., even if it matches other strings as well).


回答1:


([0-9.]*)(\/|:)([0-9]*)

Here is the regex . First group gives you IP. Third group gives you the Port number. Middle group gives separator i.e / or : used for alternation. It can be ignored.




回答2:


Use commons validator:

InetAddressValidator validator = InetAddressValidator.getInstance();
if (validator.isValid(ipAddress) {
   // cool, isn't valid
}
throw new InvalidAddressException(ipAddress);


来源:https://stackoverflow.com/questions/29757311/simple-java-regex-to-extract-ip-address-and-port-from-enclosing-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!