简体   繁体   中英

Regex pattern to find Integers in every line of the string

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

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.

You can use the Pattern.MULTILINE option when compiling your regex:

pattern = "(?<=,)\\d+";
pr = Pattern.compile(pattern, Pattern.MULTILINE);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM