如何从响应中提取字符串?

时间:2021-01-08 08:06:07

标签: java

我已经在 Google 中搜索过此事。我只想从此响应中提取这些字符串 192.168.90.2080522596656

回复是:

Ready 192.168.90.20:80 1.1
YID 5225 PID 96656
Connected

我使用了这段代码,但没有用。

public static final Pattern myPat1 = Pattern.compile("Ready (.+):(.+))",Pattern.CASE_INSENSITIVE);
public static final Pattern myPat2 = Pattern.compile("YID (.+) PID (.+))",Pattern.CASE_INSENSITIVE);

Matcher matcher1 = myPat1.matcher(response);
Matcher matcher2 = myPat2.matcher(response);

if (matcher1.matches()) {
    System.out.println(matcher1.group(1));
    System.out.println(Integer.parseInt(matcher.group(2));
} else {
    System.out.println("Error");
}

if (matcher2.matches()) {
    System.out.println(matcher2.group(1));
    System.out.println(matcher2.group(2));
} else {
    System.out.println("Error");
}

1 个答案:

答案 0 :(得分:1)

以下对我有用。

String response = """
        Ready 192.168.90.20:80 1.1
        YID 5225 PID 96656
        Connected""";
System.out.println(response);
Pattern pattern = Pattern.compile("([\\d.:]+)", Pattern.DOTALL);
Matcher matcher = pattern.matcher(response);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

输出为:

Ready 192.168.90.20:80 1.1
YID 5225 PID 96656
Connected
192.168.90.20:80
1.1
5225
96656

代码使用 java text blocks

请注意,方法 matches 尝试匹配整个字符串,而方法 find 搜索字符串中下一次出现的模式。每次调用 find 时,它都会从上一个匹配项的末尾开始搜索。

相关问题