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

时间:2016-02-21 03:08:56

标签: javascript regex

我试图找到一种方法来使用正则表达式在方括号[]括号内使用斜体,包括嵌套的方括号,但不包括括号本身。到目前为止,我提出的最好的是:

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

然而,在嵌套括号的情况下失败,例如:

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

应解析为:

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

但是上面的正则表达式产生了:

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

(文字argumentName正常而不是斜体)

1 个答案:

答案 0 :(得分:1)

一种方法是匹配每个括号组并替换替换回调中该组内的每个单词:

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

示例代码段:

&#13;
&#13;
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;
&#13;
&#13;
&#13;

<强>解释

表达式/(\[(?:\[[^\]]*\]|[^\[\]])*\])/将通过使用替换匹配您案例中的每个括号组:

(            # 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

然后在替换回调中,每个单词都用斜体包裹:

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