2

我想在下面的字符串中获取 id 字段的值,其中 inuse 字段的值为 1 。

          "version": "IPv6",
              "primarywins": null,
              "id": 3,
              "updated": 1368803376681,
              "description": null,
              "inuse": 0,
              "alias": "Shared MGMT"
           },
           {
              "computernameprefix": null,
              "protocol": "static",
              "version": "IPv4",
              "primarywins": null,
              "id": 5,
              "updated": 1368912314856,
              "description": null,
              "inuse": 1

我正在尝试下面的java代码

String regex = "\"id\": ([0-9]|[0-9][0-9]|[0-9][0-9][0-9]|[0-9][0-9][0-9][0-9]),\n.*,\n.*,\n.*\"inuse\": 1";
Pattern index_pattern2 = Pattern.compile(regex,Pattern.DOTALL);
Matcher cMatcher2 = index_pattern2.matcher(The string mentioned above);
     if(cMatcher2 != null && cMatcher2.find()
      {
        ipGrp = cMatcher2.group(1);
      }

上面代码中 ipGrp 的值始终为 3,而我想将值设为 5 关于当 in use 的值为 1 时如何获取正确 id 字段的值的任何建议

4

2 回答 2

0

Use this regex instead:

"id": ([0-9]{1,4})[^}]*"inuse": 1

Escaped:

"\"id\": ([0-9]{1,4})[^}]*\"inuse\": 1"

What did I do here?

  1. Change [0-9]|[0-9][0-9]|[0-9][0-9][0-9]|[0-9][0-9][0-9][0-9] into [0-9]{1,4}, which means there must be between 1 and 4 of [0-9].
  2. Change ,\n.*,\n.*,\n.* to [^}]*, which means any characters except }.
于 2013-05-20T11:45:26.400 回答
0

试试这个。

(?s)"id":\s?(\d+),+.*?(?:"inuse":\s)(\d)

它捕获非活动和活动,但您可以过滤结果。(?s) 导致“。” 捕获换行符。第一个捕获组捕获 id。(?: 导致第二组不捕获。第二个捕获组捕获活动标志。祝你好运。

于 2013-05-20T12:17:54.610 回答