我已经在 Google 中搜索过此事。我只想从此响应中提取这些字符串 192.168.90.20
、80
、5225
和 96656
。
回复是:
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");
}
答案 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
时,它都会从上一个匹配项的末尾开始搜索。