如何使用 Java 正则表达式获取 IP 和端口

整体流程

下面是实现该功能的步骤表格:

erDiagram
    确定输入文本 --> 编写正则表达式:匹配IP地址和端口号
    使用 Pattern 类 --> 编译正则表达式
    使用 Matcher 类 --> 匹配文本,找到符合条件的IP和端口号

具体步骤

  1. 确定输入文本

假设我们有一个字符串包含 IP 地址和端口号,例如:"Server IP: 192.168.1.1, Port: 8080"。

  1. 编写正则表达式

我们需要编写一个正则表达式来匹配 IP 地址和端口号。IP 地址的正则表达式为:

String ipRegex = "\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b";

端口号的正则表达式为:

String portRegex = "(?<=Port: )\\d+";
  1. 使用 Pattern 类

使用 Pattern 类来编译正则表达式:

Pattern ipPattern = Pattern.compile(ipRegex);
Pattern portPattern = Pattern.compile(portRegex);
  1. 使用 Matcher 类

使用 Matcher 类来匹配文本,找到符合条件的IP和端口号:

Matcher ipMatcher = ipPattern.matcher(inputText);
Matcher portMatcher = portPattern.matcher(inputText);

while (ipMatcher.find()) {
    String ip = ipMatcher.group();
    System.out.println("IP: " + ip);
}

if (portMatcher.find()) {
    String port = portMatcher.group();
    System.out.println("Port: " + port);
}

通过以上步骤,你就可以成功地使用 Java 正则表达式来获取 IP 和端口了。如果有任何疑问,欢迎随时向我提问。

结尾

希望上面的内容能够帮助你理解如何使用 Java 正则表达式来获取 IP 和端口。在教别人的过程中,也能够加深自己对知识点的理解。继续努力,加油!