Reputation: 77
I have a pattern here which finds the integers after a comma.
The problem I have is that my return value is in new lines, so the pattern only works on the new line. How do I fix this? I want it to find the pattern in every line.
All help is appreciated:
url = new URL("https://test.com");
con = url.openConnection();
is = con.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
String responseData = line;
System.out.println(responseData);
}
pattern = "(?<=,)\\d+";
pr = Pattern.compile(pattern);
match = pr.matcher(responseData); // String responseData
System.out.println();
while (match.find()) {
System.out.println("Found: " + match.group());
}
Here is the response returned as a string:
test.test.test.test.test-test,0,0,0
test.test.test.test.test-test,2,0,0
test.test.test.test.test-test,0,0,3
Here is the printout:
Found: 0
Found: 0
Found: 0
Upvotes: 2
Views: 74
Reputation: 95978
The problem is with building your String, you're assigning only the last line from the BufferedReader
:
responseData = line;
If you print responseData
before you try to match, you'll see it's only one line, and not what you expected.
Since you're printing the buffer's content using a System.out.println
, you do see the whole result, but what's getting saved to responseData
is actually the last line.
You should use a StringBuilder
to build the whole string:
StringBuilder str = new StringBuilder();
while ((line = br.readLine()) != null) {
str.append(line);
}
responseData = str.toString();
// now responseData contains the whole String, as you expected
Tip: Use the debugger, it'll make you better understand your code and will help you to find bugs very faster.
Upvotes: 4
Reputation: 1
You can use the Pattern.MULTILINE option when compiling your regex:
pattern = "(?<=,)\\d+";
pr = Pattern.compile(pattern, Pattern.MULTILINE);
Upvotes: 0