为什么这个javascript regex replace没有替换任何东西?[已关闭]

ccgok5k5  于 2022-12-25  发布在  Java
关注(0)|答案(2)|浏览(153)

**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。

这个问题是由打字错误或无法再重现的问题引起的。虽然类似的问题在这里可能是on-topic,但这个问题的解决方式不太可能帮助未来的读者。
去年关闭了。
Improve this question
我一直在尝试用正则表达式做一个简单的替换,如下所示。我遵循thisthis。但由于某种原因,下面的代码就是不工作。老实说,我看不出我做错了什么。

var equ = "77^7x";
  var base = "77";
  var exp = "7x";
  var output = equ;
  var replace = base + "^" + exp;
  var regex = new RegExp(replace, "gi");
  var newOutput = output.replace(regex, "Math.pow(" + base + "," + exp + ")");
  console.log(newOutput);

The output is not Math.pow(77^7x) as expected

I am using the python regex library
oewdyzsn

oewdyzsn1#

^是一个正则表达式元字符。您必须添加一个反斜杠。但是,由于您是从字符串转换,因此您必须添加2个反斜杠,一个作为反斜杠,另一个用于转义反斜杠。

var equ = "77\^7x";
var base = "77";
var exp = "7x";
var output = equ;
var replace = base + "^" + exp;
var regex = new RegExp(replace, "gi");
var newOutput = output.replace(regex, "Math.pow(" + base + "," + exp + ")");
console.log("Regex: %o", regex);
console.log("String searched: Math.pow(" + base + "," + exp + ")");
console.log("Output: ", newOutput);

console.log("Does the backslash at the ^ make a difference?")

var replace = base + "\\^" + exp;
var regex = new RegExp(replace, "gi");
var newOutput = output.replace(regex, "Math.pow(" + base + "," + exp + ")");
console.log("Regex: %o", regex);
console.log("String searched: Math.pow(" + base + "," + exp + ")");
console.log("Output: ", newOutput);

如您所见,正则表达式不存在于字符串"Math.pow(77,7x)"中,因此它不匹配或替换任何内容。

8yparm6h

8yparm6h2#

JSF中间文件:https://jsfiddle.net/DariusM/1zy3sf9h/2/
正如其他人提到的,^字符在Regexp中是一个特殊字符,因此需要进行转义。

var regex = new RegExp(base + "\\^" + exp, "gi");

相关问题