Reputation: 3
I already searched in Google about this matter. I just want to extract these strings 192.168.90.20
, 80
, 5225
and 96656
from this response.
The response is:
Ready 192.168.90.20:80 1.1
YID 5225 PID 96656
Connected
I used this code, but it didn't work.
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");
}
Upvotes: 0
Views: 71
Reputation: 20914
The following works for me.
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));
}
The output is:
Ready 192.168.90.20:80 1.1
YID 5225 PID 96656
Connected
192.168.90.20:80
1.1
5225
96656
The code uses java text blocks.
Note that method matches
tries to match the entire string, whereas method find
searches for the next occurrence of the pattern in the string. Each time you call find
, it starts searching from the end of the previous match.
Upvotes: 1