如何使用正则表达式按ID获取项目过滤器?

时间:2019-01-20 12:08:42

标签: regex

我有短信

{
"item":
{
  id = 1,
  something
  value="value1"
  something
}
"item":
{
  value="value2"
  something
  id = 2,
  something
}
"item":
{
  id = 3,
  something
  value="value3"
  something
}
}

我想通过ID获得价值

我尝试过

(value=.*)[\w\W]*?id = 2

但它得到的是value =“ value1”

https://regex101.com/r/xraGIQ/1

1 个答案:

答案 0 :(得分:1)

(?:(id = \d+)[^{}]*?(value="[^"\r\n]*")|(value="[^"\r\n]*")[^{}]*?(id = \d+))

将匹配所有ID /值对

说明:

(?:
    (id = \d+)              # group 1, id
    [^{}]*?                 # 0 or more any character but curly braces
    (value="[^"\r\n]*")     # group 2, value
  |                         # OR
    (value="[^"\r\n]*")     # group 3, value
    [^{}]*?                 # 0 or more any character but curly braces
    (id = \d+)              # group 4, id
)

Demo