问题描述
考虑一对IPv4
或IPv6
地址和端口,由/
或:
分隔,例如
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.
从封闭的字符串(不使用String操作函数)中提取单独字段中的2个值的非常简单的正则表达式是什么?
What would be a very simple regex to extract the 2 values in separate fields from the enclosing string (without using String manipulation functions)?
例如,类似
(?<address>[^\s,]+[^\s,:\.])((/|:)(?<port>\d*))?
在同一字符串中提取地址和端口.
extracts both address and port in the same string.
这里的目标是即使不是100%准确(即即使它也匹配其他字符串),也要使用最简单的正则表达式来实现提取.
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).
推荐答案
([0-9.]*)(\/|:)([0-9]*)
这是正则表达式.第一组给您IP.第三组为您提供端口号.中间组给出分隔符,即/或:用于交替.可以忽略.
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.
这篇关于简单的Java正则表达式从封装字符串中提取IP地址和端口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!