java 端口 正则,简单的Java正则表达式从封装字符串中提取IP地址和端口

本文介绍了如何利用简单的正则表达式从包含IPv4或IPv6地址和可选端口的字符串中提取这两部分信息。提供的解决方案是一个正则模式,能够匹配地址和端口,即使它们可能被空格或逗号分隔,并且端口是可选的。通过这个正则表达式,可以快速地从长字符串中提取IP地址和端口,尽管它可能不是100%精确。
摘要由CSDN通过智能技术生成

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

(?

[^\s,]+[^\s,:\.])((/|:)(?\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).

解决方案

([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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值