我正在尝试找到一种方法来使用正则表达式使方括号内的文本变为斜体,包括嵌套的方括号,但不包括方括号本身。到目前为止,我想到的最好的是:
text = text.replace(/(\[+)([^\[\]]+)(]+)/g, '$1<span style="font-style: italic;">$2</span>$3');
但是在嵌套括号的情况下失败,例如:
[test1] test2 ([[readonly ][optionality ][argumentType ]argumentName[ = defaultValue]]...) [test3] test4
应该解析为:
[test1] test2 ([[只读 ][可选性 ][argumentType ]argumentName [ = defaultValue]]...) [test3] test4
但上面的正则表达式会产生:
[test1] test2 ([[只读 ][可选性 ][argumentType ]argumentName[ = defaultValue]]...) [test3] test4
(文本 argumentName
正常而不是斜体)
最佳答案
一种方法是匹配每个括号组并在替换回调中替换该组中的每个单词:
string.replace(/(\[(?:\[[^\]]*\]|[^\[\]]*)*\])/g, function (match) {
return match.replace(/(\w+)/g, '*$1*');
});
示例片段:
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;
解释:
表达式 /(\[(?:\[[^\]]*\]|[^\[\]])*\])/
将匹配您的每个括号组使用交替的情况:
( # 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*');
关于JavaScript 正则表达式匹配嵌套方括号内的任何单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531821/