regex - 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
。- 在 an
id
和 next之间array
,可以有任意数量的"attribute":<value>
对。 - an 的值
id
不能包含在{}
or中[]
。 - 保证an 的值
id
不包含任何,
字符。最后的,
字符,例如"id":73642,
,不被视为值的一部分,因为它用作分隔符。 - 正则表达式只能是 PCRE。
- 这并不是真正的约束,但我更喜欢可以在此处确认的解决方案。
我的尝试
"id":([^,]+).*?"array":\[(?(?=])]|\K)
我天真地认为\K
也会重置捕获组,但事实并非如此,因为正则表达式匹配所有id。
解决方案
考虑到您的所有约束,您可能使用的最近似的正则表达式是
"id":"([^,]+)[^][]*?"array":\[]
请参阅此正则表达式演示。
细节
"id":"
- 文字"id":"
字符串([^,]+)
- 第 1 组:除逗号之外的任何一个或多个字符[^][]*?
[
- 除and以外的任何 0 个或多个字符]
,尽可能少"array":\[]
- 文字"array":[]
字符串。
推荐阅读
- javascript - Javascript:将字符串转换为数组
- angular - 为了在 .NET Core 中开发 Angular + 微服务架构中的 Front,哪种解决方案更好?
- html - 无法以某种方式解开 flex 容器内的图像?
- javascript - React Router useNavigate hook 不需要的滚动到顶部 onclick
- hybris - 后台:编辑器区域中的 CSV 上传功能
- sql - Oracle - 使用第二个表中的行更新第一个表中的数据
- python - 如何将属性添加到表单标签本身,而不仅仅是 Django 中的字段?
- javascript - 如何将测试数据(包含、数组、json对象、变量)导出到另一个js文件?
- flutter - 颤振中的矩形框
- asp.net-mvc - 在 IIS 上编辑已部署的 asp.net MVC5 应用程序的视图