【问题标题】:How to catch groups occurring more than once using regex in Java如何在 Java 中使用正则表达式捕获多次出现的组
【发布时间】:2020-01-28 15:59:49
【问题描述】:

给定这个示例输入字符串。

String str = 
   "[{\"ID\":\"A001\",\"Name\":\"Captain America\",\"State\":\"Brooklyn\"},
     {\"ID\":\"A002\",\"Name\":\"Iron Man\",\"State\":\"New York\"}]"

我正在尝试使用正则表达式来提取与键“名称”关联的所有值。

Pattern p = Pattern.compile(".*\"name\":(\".*\").*");  
Matcher m = p.matcher(str);  
if(m.find()){
   System.out.println(m.group(1));
   System.out.println(m.group(2));            
}

我正在尝试实现以下输出:

Captain America
Iron Man

但上面的代码却产生了这个:

"Iron Man","state":"New York"

还希望获得有关直接在 Java JSONObject 上使用相同字符串数据执行类似操作的技术建议。

【问题讨论】:

  • 不要使用正则表达式解析 JSON。只是不要。
  • GSON 是一个很好的 JSON 解析器。
  • 这在字符串中不可能吗?
  • 我在这里处理 HTTPResponse。在这种情况下,我的 JSON 如下 {"headers":{} ,"body": "[{\"ID\":\"A001\",\"Name\":\"Captain America\",\ "州\":\"布鲁克林\"},{\"ID\":\"A002\",\"姓名\":\"钢铁侠\",\"州\":\"纽约\" }]" ,"status":200} 我将如何帮助这里的有需要的人
  • 根据我的理解,body 的值是 String 对吧?

标签: java regex


【解决方案1】:

你可以这样做:

public static void main(String[] args) throws IOException {
    String str = "[{\"ID\":\"A001\",\"Name\":\"Captain America\",\"State\":\"Brooklyn\"},{\"ID\":\"A002\",\"Name\":\"Iron Man\",\"State\":\"New York\"}]";
    Pattern p = Pattern.compile("(?<=\"Name\":\")(.*?)(?=\",\"State\")");  
    Matcher m = p.matcher(str);
    while(m.find()){
        System.out.println(m.group(1));
    }
}

这将打印:

Captain America
Iron Man

更好的选择是使用JSON Parser...

【讨论】:

  • 如何使用 JSON 解析器?我试过做 JSONObject obj = new JSONObject(str) 这是错的吗?
  • 您需要阅读您使用的任何库的文档...
  • 提供的正则表达式仍然只返回一个值
  • 假设我有你所说的 JSON 对象。格式为 {"headers":{} ,"body": "[{\"ID\":\"A001\",\"Name\":\"Captain America\",\"State\" :\"布鲁克林\"},{\"ID\":\"A002\",\"姓名\":\"钢铁侠\",\"州\":\"纽约\"}]" , "status":200} 这里怎么取名字?
  • @Srikanth 不,它返回name 的所有值,您是否尝试运行它。我只是在 Eclipse 中运行它,它会打印出我所说的 Captain America 和 Iron Man...完全复制我的代码并运行它...
猜你喜欢
  • 1970-01-01
  • 2020-12-16
  • 1970-01-01
  • 1970-01-01
  • 2015-07-24
  • 2013-09-29
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
相关资源
最近更新 更多