Javascript:仅替换某些短语中的字母

时间:2012-07-27 17:34:59

标签: javascript regex

超过here我被要求用我的一条评论形成一个新问题,所以我在这里。我想知道是否有可能只替换某些单词中的短语。例如:替换BAB中的CBABAC而不是BAB中的DABABCC,谢谢!

2 个答案:

答案 0 :(得分:2)

使用lookahead

BAB(?=AC)

<强>解释

"BAB" +      // Match the characters “BAB” literally
"(?=" +      // Assert that the regex below can be matched, starting at this position (positive lookahead)
   "AC" +       // Match the characters “AC” literally
")"  

BAB(?!CC)

<强>解释

"BAB" +      // Match the characters “BAB” literally
"(?!" +      // Assert that it is impossible to match the regex below starting at this position (negative lookahead)
   "CC" +       // Match the characters “CC” literally
")"  

答案 1 :(得分:0)

你没有说明替换逻辑的基础是什么,所以这是一个普遍的答案。

正如一些人所提到的,你可以使用前瞻,但JavaScript的一个主要烦恼是它本身不支持lookbehinds,所以你只有一半的解决方案。

缺少后视的常见解决方法是匹配(而不是锚定)您感兴趣的位之前的内容,然后将其重新插入回调中。

假设我想将foo的所有实例替换为bar,其前面是一个数字,并以数字为前提。

var str = 'foo 1foo1 foo2';
console.log(str.replace(/(\d)foo(?=\d)/g, function($0, $1) {
    return $1+'bar';
})); //foo 1bar1 foo1

所以我使用前瞻作为简单部分,并使用回调来弥补缺乏外观。

在JS中实现了lookbehind, including one I wrote ,其中正面或负面的lookbehind作为额外参数传递。使用它,这将得到与上面相同的结果:

console.log(str.replace2(/foo(?=\d)/g, 'bar', '(?<=\\d)'));
相关问题