实际上我想替换一个字符串,除非它出现在圆括号中。
例如:
JAVA is a nice language. (JAVA) has lots of features. JAVA is portable. (JAVA) even comes in 64 bit.
现在如果我用 C 替换 JAVA:
然后期望的输出是:
C is a nice language. (JAVA) has lots of features. C is portable. (JAVA) even comes in 64 bit.
甚至java也可以作为子字符串出现
XJAVAX is a nice language. (XJAVAX) has lots of features. JAVA is portable. (JAVA) even comes in 64 bit.
现在,如果我用 C 替换 JAVA:
然后预期的输出:
XCX is a nice language. (XJAVAX) has lots of features. C is portable. (JAVA) even comes in 64 bit.
最佳答案
由于 JavaScript 没有后视,最简单的方法可能是交替:
str = str.replace(/\(JAVA\)|JAVA/g, function(m) {
return m === "(JAVA)" ? m : "C";
// Or
// return m.length === 6 ? m : "C";
});
除此之外,您开始尝试 simulate look-behind ,这在某些方面是可能的,但很麻烦。
关于javascript - js中基于正则表达式的替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8239540/