简体   繁体   English

JavaScript正则表达式匹配嵌套方括号内的任何单词?

[英]JavaScript Regex to match any words within nested square brackets?

I'm trying to find a way to use regex to make text italic inside of square [] brackets, inclusive of nested square brackets, but not the brackets themselves. 我试图找到一种方法来使用正则表达式在square []括号内使用斜体,包括嵌套的方括号,但不包括括号本身。 So far the best I've come up with is: 到目前为止,我提出的最好的是:

text = text.replace(/(\[+)([^\[\]]+)(]+)/g, '$1<span style="font-style: italic;">$2</span>$3');

however that fails in the case of nested brackets, something like: 但是在嵌套括号的情况下会失败,例如:

[test1] test2 ([[readonly ][optionality ][argumentType ]argumentName[ = defaultValue]]...) [test3] test4

Should parse to: 应解析为:

[ test1 ] test2 ([[ readonly ][ optionality ][ argumentType ] argumentName [ = defaultValue ]]...) [ test3 ] test4 [ test1 ] test2([[ readonly ] [ optionality ] [ argumentType ] argumentName [ = defaultValue ]] ...)[ test3 ] test4

But instead the above regex produces: 但相反,上述正则表达式产生:

[ test1 ] test2 ([[ readonly ][ optionality ][ argumentType ]argumentName[ = defaultValue ]]...) [ test3 ] test4 [ test1 ] test2([[ readonly ] [ optionality ] [ argumentType ] argumentName [ = defaultValue ]] ...)[ test3 ] test4

(with the text argumentName normal instead of italics) (使用text argumentName而不是斜体)

One approach is to match each bracket group and replace each word within that group inside of the replace callback: 一种方法是匹配每个括号组并替换替换回调内该组内的每个单词:

string.replace(/(\[(?:\[[^\]]*\]|[^\[\]]*)*\])/g, function (match) {
  return match.replace(/(\w+)/g, '*$1*');
});

Example Snippet: 示例代码段:

 var string = "[test1] test2 ([[readonly ][optionality ][argumentType ]argumentName[ = defaultValue]]...) [test3] test4"; var result = string.replace(/(\\[(?:\\[[^\\]]*\\]|[^\\[\\]]*)*\\])/g, function (match) { return match.replace(/(\\w+)/g, '*$1*'); }); document.body.textContent = result; 

Explanation : 说明

The expression /(\\[(?:\\[[^\\]]*\\]|[^\\[\\]])*\\])/ will match each bracket group in your case by utilizing an alternation: 表达式/(\\[(?:\\[[^\\]]*\\]|[^\\[\\]])*\\])/将通过使用替换匹配您案例中的每个括号组:

(            # Capturing group
\[           # Opening bracket
(?:          # Non-capturing group
\[[^\]]*\]   # Match nested brackets that don't contain other brackets
|            # Alternation.. or:
[^\[\]]*     # Match non-bracket characters
)*           # Close the non-capturing group and match it zero or more times
\]           # Closing bracket
)            # Close the capturing group

Then in the replace callback, each word is wrapped with the italics: 然后在替换回调中,每个单词都用斜体包装:

match.replace(/(\w+)/g, '*$1*');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM