简体   繁体   English

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

[英]Regex replace with number after capture group?

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. 问题在于$1是一个捕获组,而0只是我要放入替换中的数字。 But regex thinks I'm asking for capture group $10 instead of $1 and then a zero after it. 但是正则表达式认为我要的是捕获组$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。

Your code indeed works just fine. 您的代码确实可以正常工作。 In JavaScript regular expression replacement syntax $10 references capturing group 10 . 在JavaScript正则表达式替换语法中, $10引用捕获组10 However, if group 10 has not been set, group 1 gets inserted then the literal 0 afterwards. 但是,如果尚未设置组10 ,则将插入组1 ,然后再输入文字0

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

Your code does work unless I'm missing something: 您的代码可以正常工作,除非我遗漏了一些东西:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM