Regex.Replace:如何使用$ groups后跟数字

时间:2022-09-12 19:28:23

With Regex::Replace we can use $1, $2, ... to match corresponding groups. But how can I use $1 followed by number. E.g. to replace 6 with 678?

使用Regex :: Replace,我们可以使用$ 1,$ 2,...来匹配相应的组。但是我如何使用$ 1后跟数字。例如。用678替换6?

 Regex::Replace(text, "(6)", '$178');

3 个解决方案

#1


20  

You need to use the alternate syntax:

您需要使用备用语法:

Regex::Replace(text, "(6)", "${1}78");

#2


1  

You can use backreferences to capture a named group and replace that named group with whatever you want. view this link

您可以使用反向引用来捕获命名组,并将该命名组替换为您想要的任何组。查看此链接

#3


0  

It seems I can use $`

好像我可以用$`

Regex::Replace(text, "(6)", '$1$`78');

#1


20  

You need to use the alternate syntax:

您需要使用备用语法:

Regex::Replace(text, "(6)", "${1}78");

#2


1  

You can use backreferences to capture a named group and replace that named group with whatever you want. view this link

您可以使用反向引用来捕获命名组,并将该命名组替换为您想要的任何组。查看此链接

#3


0  

It seems I can use $`

好像我可以用$`

Regex::Replace(text, "(6)", '$1$`78');