捕获组后正则表达式替换为数字?

时间:2021-04-26 10:24:47

I have a regex pattern like this:

我有这样的正则表达式模式:

([0-9]*)xyz

I wish to do substitution like this:

我希望做这样的替换:

$10xyz

The problem is that the $1 is a capture group and the 0 is just a number I want to put into the substitution. But regex thinks I'm asking for capture group $10 instead of $1 and then a zero after it.

问题是$ 1是一个捕获组,0只是我想要替换的数字。但正则表达式认为我要求捕获组10美元而不是1美元,之后是零。

How do I reference a capture group and immediately follow it with a number?

如何引用捕获组并立即使用数字跟随它?

Using JavaScript in this case.

在这种情况下使用JavaScript。

UPDATE As pointed out below, my code did work fine. The regex tester I was using was accidentally set to PCRE instead of JavaScript.

更新如下所述,我的代码确实工作正常。我正在使用的正则表达式测试程序被意外设置为PCRE而不是JavaScript。

2 个解决方案

#1


4  

Your code indeed works just fine. In JavaScript regular expression replacement syntax $10 references capturing group 10. However, if group 10 has not been set, group 1 gets inserted then the literal 0 afterwards.

你的代码确实很好用。在JavaScript正则表达式替换语法$ 10中引用捕获组10.但是,如果尚未设置组10,则组1将被插入,然后插入文字0。

var r = '123xyz'.replace(/([0-9]*)xyz/, '$10xyz');
console.log(r); //=> "1230xyz"

#2


1  

Your code does work unless I'm missing something:

你的代码确实有效,除非我遗漏了一些东西:

var str = "3xyz";
var str1 = str.replace(/([0-9]*)xyz/, "$10xyz");
alert(str1); // alerts 30xyz

#1


4  

Your code indeed works just fine. In JavaScript regular expression replacement syntax $10 references capturing group 10. However, if group 10 has not been set, group 1 gets inserted then the literal 0 afterwards.

你的代码确实很好用。在JavaScript正则表达式替换语法$ 10中引用捕获组10.但是,如果尚未设置组10,则组1将被插入,然后插入文字0。

var r = '123xyz'.replace(/([0-9]*)xyz/, '$10xyz');
console.log(r); //=> "1230xyz"

#2


1  

Your code does work unless I'm missing something:

你的代码确实有效,除非我遗漏了一些东西:

var str = "3xyz";
var str1 = str.replace(/([0-9]*)xyz/, "$10xyz");
alert(str1); // alerts 30xyz