繁体   English   中英

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

[英]Regex pattern to find Integers in every line of the string

我在这里有一个模式,可以在逗号后找到整数。

我的问题是我的返回值位于新行中,因此该模式仅适用于新行。 我该如何解决? 我希望它能在每一行中找到模式。

感谢所有帮助:

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());
}

这是作为字符串返回的响应:

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

这是打印输出:

Found: 0
Found: 0
Found: 0

问题在于构建String,您只分配了BufferedReader的最后一行:

responseData = line;

如果在尝试匹配之前打印出responseData ,您将看到它只是一行,而不是您所期望的。

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

您应该使用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

提示:使用调试器,它将使您更好地理解代码,并可以帮助您更快地发现错误。

您可以在编译正则表达式时使用Pattern.MULTILINE选项:

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

暂无
暂无

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

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