[英]Regex matching Text with Square Brackets
Using javascript I need to get the text and tokens from string like: 使用JavaScript,我需要从字符串获取文本和令牌,例如:
"type":"homePhone","means":"$[createJohnRequest.contactInfo[type=homePhone].means]"
Such that a regex will return: 这样正则表达式将返回:
$[createJohnRequest.contactInfo[type=homePhone].means]
I have a few attempts at this but none that work: 我对此进行了几次尝试,但都没有成功:
/(\$\[(.*?]))/g
will return: $[createJohnRequest.contactInfo[type=homePhone] 将返回:$ [createJohnRequest.contactInfo [type = homePhone]
/(\$\[(.*]))/g
This works in the above case but is way too greedy for a case like: 这在以上情况下有效,但对于以下情况来说太贪婪了:
{"firstName":"$[user.firstName]","userName":"$[user.username1]","details":
{"description":"this is $[user.username1] the $[user.username2] text th $[user.username3]
at conta$[user.username4]ins the terms we want to find. $[final.object]"}}
Ideally I want a single regex to match both in multiline text: 理想情况下,我希望单个正则表达式在多行文本中匹配两者:
some text here $[some.value.here]bunch of noisy text in between here
some more text here$[some.value[index]goes.here]some more noise here
$[some.value.here] and $[some.value[index].goes.here] $ [some.value.here]和$ [some.value [index] .goes.here]
Anyone have any ideas to point me in the right direction? 任何人有任何想法可以指引我正确的方向吗?
I am leaning toward using $[some token]$ instead which is pretty simple to capture. 我倾向于使用$ [some token] $代替,这很容易捕获。
You want something like this, as long as the bracket nesting level is limited to two: 您需要这样的东西,只要方括号嵌套级别限制为两个即可:
/\$\[(\[.*]|.)*?\]/g
In English: 用英语:
a dollar sign followed by
a bracketed sequence whose content is
any number of occurrences of
either
a bracketed subsequence whose content is anything
or something else
See http://regexr.com/39iht . 参见http://regexr.com/39iht 。
If you want to support deeper nesting, I suggest you write a little function to build the regexp for you, so you don't go insane: 如果您想支持更深层的嵌套,建议您编写一个小函数为您构建正则表达式,这样就不会发疯了:
function make_regexp(level) {
var build = "\\[.*?]";
while (level--) {
build = "(\\[" + build + "]|.)*?";
}
return RegExp("\\$" + build, "g");
}
> make_regexp(3)
/\$(\[(\[(\[.*]|.*)*?]|.*)*?]|.*)*?/g
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.