0

这是我原来的字符串:

String response = "attributes[{"id":50,"name":super},{"id":55,"name":hello}]";

我正在尝试解析字符串并提取所有id值,例如
50
55

Pattern idPattern = Pattern.compile("{\"id\":(.*),");
Matcher matcher = idPattern.matcher(response);

while(matcher.find()){
    System.out.println(matcher.group(1));
}


当我尝试打印该值时,我得到一个异常: java.util.regex.PatternSyntaxException: Illegal repetition
过去对正则表达式没有太多经验,但在网上找不到简单的解决方案。
感谢任何帮助!

4

3 回答 3

3
Pattern.compile("\"id\":(\\d+)");
于 2012-11-08T16:38:37.697 回答
2

{是正则表达式中的保留字符,应该转义。

\{\"id\":(.*?),

编辑:如果您要使用 JSON,您应该考虑使用专用的 JSON 解析器。它会让你的生活更轻松。请参阅在 Java 中解析 JSON 对象

于 2012-11-08T16:38:08.573 回答
2

不要使用贪婪的匹配运算符,例如匹配任何字符*的 a 。.不必要的。如果要提取数字,可以使用\d.

"id":(\d+)

在 Java 字符串中,

Pattern.compile("\"id\":(\\d+)");
于 2012-11-08T16:39:39.180 回答