简体   繁体   English

正则表达式模式可在字符串的每一行中查找整数

[英]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 : 问题在于构建String,您只分配了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. 如果在尝试匹配之前打印出responseData ,您将看到它只是一行,而不是您所期望的。

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. 既然你打印使用缓冲区内容System.out.println看到整个的结果,但什么是得到保存到responseData实际上是最后一道防线。

You should use a StringBuilder to build the whole string: 您应该使用StringBuilder构建整个字符串:

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.MULTILINE选项:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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