正则表达式以匹配JSON列表中的特定多行对象 [英] Regex to match specific, multiline object in JSON list
问题描述
我使用的JSON列表如下所示:
I work with JSON lists which can look somewhat like the following:
[
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$unauthenticated",
"permission": "DENY"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$owner",
"permission": "ALLOW"
}
]
编写正则表达式以正确地仅提取包含单词 $ everyone
的列表项的正确方法是什么?我需要提取整个对象,所以正确的结果应该是:
What would be the proper way to write a regex which correctly extracts only the list item which contains the word $everyone
? I need to extract the entire object, so the correct result should be:
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "DENY"
}
我尝试了类似 \ {(?s).* Everyone(?s).* \}
之类的方法,但这将与列表中的第一个和最后一个大括号和最后一个大括号匹配,介于两者之间.
I have tried something like \{(?s).*everyone(?s).*\}
, but this will match the first and last opening and closing curly bracket in the list, with everything in between.
推荐答案
对于在IDE中进行一次搜索和替换的一次性任务:
For a one-off task of search and replace in IDE:
\{[^}]*?everyone[^}]*\}
如果您需要 $
,请使用以下任一方法:
If you need the $
, use either:
\{[^}]*?\$everyone[^}]*\}
\{[^}]*?[$]everyone[^}]*\}
而不是(?s).*
,它允许在 {
和 Everyone
之间以及在 Everyone
之间的任何内容和}
,我将其限制为 [^}] *?
,这不允许在免费"部分中使用}
.
Instead of (?s).*
which allows anything in between {
and everyone
and between everyone
and }
, I restrict it to [^}]*?
, which disallows }
in the "free" part.
正则表达式中有很多假设,因此一般情况下不要使用它.
A lot of assumptions is made in the regex, so don't use it in general case.
这篇关于正则表达式以匹配JSON列表中的特定多行对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!