[英]Simple Java regex to extract IP address and port from enclosing string
Consider a pair of IPv4
or IPv6
address and port, separated by either /
or :
, eg 考虑一对
IPv4
或IPv6
地址和端口,由/
或:
分隔,例如
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)? 从封闭字符串中提取单独字段中的2个值(不使用字符串操作函数)会是一个非常简单的正则表达式吗?
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 (ie, even if it matches other strings as well). 这里的目标是使用最简单的正则表达式进行提取,即使它不是100%准确(即,即使它也匹配其他字符串)。
([0-9.]*)(\/|:)([0-9]*)
Here is the regex . 这是正则表达式。 First group gives you IP.
第一组给你IP。 Third group gives you the Port number.
第三组为您提供端口号。 Middle group gives separator ie / or : used for alternation.
中间组给出分隔符ie /或:用于交替。 It can be ignored.
它可以被忽略。
Use commons validator : 使用commons验证器 :
InetAddressValidator validator = InetAddressValidator.getInstance();
if (validator.isValid(ipAddress) {
// cool, isn't valid
}
throw new InvalidAddressException(ipAddress);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.