我试图找到一种使用正则表达式的方法使方括号[]中的文本变为斜体,包括嵌套方括号,但不包括方括号本身。 到目前为止,我想出的最好的方法是:
text = text.replace(/(\[+)([^\[\]]+)(]+)/g, '$1$2$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正常而不是斜体)
您无法使用(仅)正则表达式解决此问题,您需要编写解析器。
看看这个:gist.github.com/acdcjunior/cfee862d1618e693bdc6这是一个解析器。
一种方法是匹配每个括号组,并在replace回调内替换该组中的每个单词:
string.replace(/(\[(?:\[[^\]]*\]|[^\[\]]*)*\])/g, function (match) {
<