首页 > 解决方案 > PCRE - 当且仅当更远的地方适合时匹配每个

问题描述

我正在努力解决这个问题。我需要匹配每次出现的情况id,以便下一个array必须为空(即[])。

{
    "objs":[
        {
            "id":73642,
            "henro":null,
            "oo":0,
            "array":["boxed"],
            "hehe":"haha"
        },
        {
            "holy":"guacamole",
            "id":"pick me!",
            "henro":null,
            "meow":"rrrraawwrr",
            "oo":null,
            "array":[],
            "say":"what"
        },
        {
            "not id":null,
            "null":null,
            "id":"don't pick me",
            "henro":3781237,
            "2173881":"henro",
            "oo":"hehe",
            "array":["baz"]
        },
        {
            "id":"pick me 2!",
            "henro":null,
            "oo":0,
            "array":[],
            "ola":"elo"
        }
    ]
}

重要的提示

我已经格式化数据只是为了使其可读。请改用紧凑版本(悬停在上面):

{"objs":[{"id":73642,"henro":null,"oo":0,"array":["boxed"],"hehe":"haha"},{"holy":"guacamole","id":"pick me!","henro":null,"meow":"rrrraawwrr","oo":null,"array":[],"say":"what"},{"not id":null,"null":null,"id":"don't pick me","henro":3781237,"2173881":"henro","oo":"hehe","array":["baz"]},{"id":"pick me 2!","henro":null,"oo":0,"array":[],"ola":"elo"}]}


目标

id必须匹配后面跟的所有值"array":[]。因此,在示例中,唯一有效的匹配是"pick me!"and "pick me 2!"。两者必须匹配(全局模式)。


约束


我的尝试

"id":([^,]+).*?"array":\[(?(?=])]|\K)

我天真地认为\K也会重置捕获组,但事实并非如此,因为正则表达式匹配所有id。

标签: regexpcre

解决方案


考虑到您的所有约束,您可能使用的最近似的正则表达式是

"id":"([^,]+)[^][]*?"array":\[]

请参阅此正则表达式演示

细节

  • "id":"- 文字"id":"字符串
  • ([^,]+)- 第 1 组:除逗号之外的任何一个或多个字符
  • [^][]*?[- 除and以外的任何 0 个或多个字符],尽可能少
  • "array":\[]- 文字"array":[]字符串。

推荐阅读