正则表达式-在第一个和最后一个出现的双方括号之间进行匹配 [英] Regex - match between 1st and last occurrence of double square brackets
问题描述
我要匹配位于" 内的任何文本值和非文本值,但仅在 [[]和]]
I'm looking to match any text and non text values, located within " " , but only between the 1st and the last instance of [[ and ]]
window.google.ac.h([[text], [["text1",0],["text2",0,[3]],["text3",0 ],["text4",0,[3]],["text5",0],["text6",0],["text7",0 ]] ,{"q":"hygjgjhbjh","k":1}])
window.google.ac.h(["text",[["text1",0],["text2",0,[3]],["text3",0],["text4",0,[3]],["text5",0],["text6",0],["text7",0 ]],{"q":"hygjgjhbjh","k":1}])
到目前为止,我已经通过使用(.*?)",0设法获得了一些结果(远非理想). 我遇到的问题是,要么一直匹配到
So far I've managed to get some results (far from ideal) by using: "(.*?)",0 The issue I have is the it either matches all the way until
"text4",0,[3]]
"text4",0,[3]]
或从
[文本",
["text",
我只需要匹配 text1 text2 text3 .. text7
注意:第一个和最后一个之间的双方括号位置和实例的nr不一致.
Notes: double square bracket position and nr of instances, between the 1st and the last is not consistent.
感谢您的帮助!
我正在使用 http://regexr.com/进行测试
推荐答案
好吧,您没有说哪种语言,而是使用.NET regex(在很大程度上遵循Perl标准),它是使用以下正则表达式的全局匹配将包含您想要的值:
Well, you didn't say which language, but using .NET regex (which largely follows the Perl standard), the first match groups of all the matches of a global match using the following regex will contain the values you want:
(?<=\[\[.*)"(.+?)"(?=.*\]\])
仅在"(.+?)"
上的全局匹配将返回匹配,其第一个匹配组将包含引号之间的字符.后置断言(?<=\[\[.*)
告诉它仅包括在后面的任意位置(即在[[
的第一个实例之后)存在[[
的情况.类似地,超前断言(?=.*\]\])
告诉它仅包括前面出现]]
的情况,即在]]
的最后一个实例之前.
A global match on "(.+?)"
alone would return matches whose first match groups would contain the characters between the quotes. The lookbehind assertion (?<=\[\[.*)
tells it to include only cases where there is a [[
anywhere behind, i.e. after the first instance of [[
. Similarly, the lookahead assertion (?=.*\]\])
tells it to include only cases where there is a ]]
anywhere ahead, i.e. before the last instance of ]]
.
我使用PowerShell对此进行了测试.进行全局匹配并提取所有结果的第一个匹配组的确切语法取决于语言.
I tested this using PowerShell. The exact syntax to do a global match and extract the first match groups of all the results will depend on the language.
这篇关于正则表达式-在第一个和最后一个出现的双方括号之间进行匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!