简体   繁体   English

在正则表达式替换字符串中转义$

[英]Escape $ in regex replacement string

I want to turn the string dkfj-dkfj-sflj into dkfj-woop$dkfj-sflj . 我想将字符串dkfj-dkfj-sflj转换为dkfj-woop$dkfj-sflj

Here's what I've tried: 这是我尝试过的:

var my_string = "dkfj-dkfj-sflj";
var regex = new RegExp("(\\w+)-(\\w+)-(\\w+)", "g");
console.log(my_string.replace(regex, "$1$woop[\$$2]$3");

And my result is: dkfj-woop$2-sflj . 我的结果是: dkfj-woop$2-sflj Because the "$" is in front of the "$2" capture group, it messes up that capture group. 因为“ $”在“ $ 2”捕获组的前面,所以它弄乱了该捕获组。

Assuming I want the structure of my regex and capture group string to stay the same, what's the right way to escape that "$" so it works? 假设我希望我的正则表达式和捕获组字符串的结构保持不变,什么是转义“ $”使其正确的正确方法呢?

That isn't how you escape a $ for replace . 这不是您为了replace逃脱$的方法。 Backslash escaping works at the parser level, functions like replace cannot give special meaning to new escape sequences like \\$ because they don't even see the \\$ . 反斜杠转义在解析器级别起作用,诸如replace功能无法给\\$类的新转义序列赋予特殊含义,因为它们甚至看不到 \\$ The string "\\$" is exactly equivalent to the string "$" , both produce the same string. 字符串"\\$"与字符串"$"完全等效,两者都产生相同的字符串。 If you wanted to pass a backslash and a dollar sign to a function, it's the backslash itself that requires escaping: "\\\\$" . 如果要向函数传递反斜杠和美元符号,则反斜杠本身需要转义: "\\\\$"

Regardless, replace expects you to escape a $ with $$ . 无论如何, replace希望您能逃脱$$$ You need "$1$woop[$$$2]$3" ; 您需要"$1$woop[$$$2]$3" a $$ for the literal $ , and $2 for he capture group. $$代表字面的$$2代表捕获组。

Read Specifying a string as a parameter in the replace docs. 请参阅在replace文档中将字符串指定为参数

Use $$ in the replacement part to print a literal $ symbol and you don't need to have a character class in the replacement part if your pattern was enclosed within forward slashes. 在替换部分中使用$$可以打印文字$符号,并且如果您的图案包含在正斜杠中,则无需在替换部分中包含字符类。

> var my_string = "dkfj-dkfj-sflj";
undefined
> my_string.replace(/(\w+)-\w+-(\w+)/, "$1-woop$$$1-$2")
'dkfj-woop$dkfj-sflj'

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

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