匹配正则表达式中的字符*而不是*

Match the character * and not the * in regex?

本文关键字:字符 正则表达式      更新时间:2023-09-26

我有以下字符串Item * '* and *。我想匹配所有的*字符,跳过'*字符。

var input = "Item * ''* and *";
var output = (some regex magic happens here)
alert(output); // Item foo '* and foo

有什么想法吗?

以下是我认为您正在尝试实现的目标:

var input = "Item * ''* and *"; 
var repl = "foo";
var output = input.replace(/('''*)|'*/g, function(_, a) { return a || repl; });
alert(output); // Item foo '* and foo

基本上,当您向replace方法提供函数时,它会将匹配和任何匹配的组作为参数传递给该函数,并使用返回值作为替换字符串。在这种情况下,由于参数a只有在与"'*"匹配时才有值,因此它将不修改该匹配。否则,它将用"foo"替换它。