4

我试图找到一个正则表达式,当它前面没有另一个特定字符串时(在我的例子中,当它前面没有“http://”时)将匹配一个字符串。这是在JavaScript中,我在 Chrome 上运行(没关系)。

示例代码是:

var str = 'http://www.stackoverflow.com www.stackoverflow.com';
alert(str.replace(new RegExp('SOMETHING','g'),'rocks'));

我想用一个正则表达式替换 SOMETHING,意思是“匹配 www.stackoverflow.com,除非它前面有 http://”。然后警报自然会说“ http://www.stackoverflow.com Rocks”。

任何人都可以帮忙吗?感觉就像我尝试了以前答案中的所有内容,但没有任何效果。谢谢!

4

3 回答 3

4

由于 JavaScript 正则表达式引擎不支持“lookbehind”断言,因此不可能使用纯正则表达式。不过,有一种解决方法,涉及replace回调函数:

var str = "As http://JavaScript regex engines don't support `lookbehind`, it's not possible to do with plain regex. Still, there's a workaround";

var adjusted = str.replace(/\S+/g, function(match) {
  return match.slice(0, 7) === 'http://'
    ? match
    : 'rocks'
});
console.log(adjusted);

您实际上可以为这些函数创建一个生成器:

var replaceIfNotPrecededBy = function(notPrecededBy, replacement) {
   return function(match) {
     return match.slice(0, notPrecededBy.length) === notPrecededBy
       ? match
       : replacement;
   }
};

...然后在其中使用它replace

var adjusted = str.replace(/\S+/g, replaceIfNotPrecededBy('http://', 'rocks'));

JS小提琴

于 2013-09-19T00:11:46.410 回答
0

raina77ow's answer reflected the situation in 2013, but it is now outdated, as the proposal for lookbehind assertions got accepted into the ECMAScript spec in 2018.

See docs for it on MDN:

Characters Meaning
(?<!y)x Negative lookbehind assertion: Matches "x" only if "x" is not preceded by "y". For example, /(?<!-)\d+/ matches a number only if it is not preceded by a minus sign. /(?<!-)\d+/.exec('3') matches "3". /(?<!-)\d+/.exec('-3') match is not found because the number is preceded by the minus sign.

Therefore, you can now express "match www.stackoverflow.com unless it's preceded by http://" as /(?<!http:\/\/)www.stackoverflow.com/:

const str = 'http://www.stackoverflow.com www.stackoverflow.com';
console.log(str.replace(/(?<!http:\/\/)www.stackoverflow.com/g, 'rocks'));

于 2022-02-03T11:28:37.323 回答
-1

这也有效:

var variable = 'http://www.example.com www.example.com';
alert(variable.replace(new RegExp('([^(http:\/\/)|(https:\/\/)])(www.example.com)','g'),'$1rocks'));

警报显示“ http://www.example.com摇滚”。

于 2013-09-19T13:28:06.117 回答