这是不可能的。
您无法将此正则表达式转换为 JavaScript 风格,因为它使用了 JavaScript 正则表达式引擎不支持的递归 (?R)。
我会建议一种不同的方法。我假设您要删除尖括号中的所有内容,包括周围的括号,除非在 <code>...</code> 块中找到这些括号。对?好吧,JavaScript 正则表达式(甚至不支持后向断言)可以为您做的最好的事情是:
result = subject.replace(/<(?!\/code)[^<>]*>\s*(?!(?:(?!<code>)[\s\S])*<\/code>)/g, "");
这是做什么的(不幸的是,JavaScript 甚至也不支持冗长的正则表达式;这个正则表达式很难理解......):
< # Match a <
(?!/code) # (unless it's part of a </code> tag)
[^<>]* # and any number of non-bracket characters
> # followed by >
\s* # and any whitespace.
(?! # Assert that we can't match the following here:
(?: # The following expression:
(?! # Unless we are right before a
<code> # <code> tag
) # Then match
[\s\S] # any character
)* # any number of times
</code> # until the next </code> tag
) # End of lookahead assertion
这确保我们只匹配一个标签,如果接下来的下一个<code>/</code>标签是一个开始<code>标签,而不是一个结束</code>标签(或者如果根本没有这样的标签)。
所以它变了
This <b> is bold </b> text,
but we want <code> these <i> tags <b> here </b> to remain </i> </code>
while those <b> can be deleted</b>.
进入
This is bold text,
but we want <code> these <i> tags <b> here </b> to remain </i> </code>
while those can be deleted.
如果你也想自己删除code标签,你可以使用
result = subject.replace(/<[^<>]*>\s*(?!(?:(?!<code>)[\s\S])*<\/code>)|<code>\s*/g, "");
这将给出结果
This is bold text,
but we want these <i> tags <b> here </b> to remain </i>
while those can be deleted.
如果code 标签可以嵌套,这些正则表达式都不起作用。