Pre:我有自己的库,我在其中使用 Coffescript 中的命名空间模块和类。这就像在 Ruby “namspace::module::class” 中一样,因为不允许使用 '::' 作为我替换的类名 Module::ClassName
与 Module$$ClassName
-> replace(/\$\$/g,'::')
,好吧。
现在我很难反向操作:replace(/::/g,'$$')
结果 Module$ClassName
只有一美元($)
所以我玩了一下
a="a:a::b:b::c:c"
a.replace(':','$') #-> "a$a::b:b::c:c" clear only first
a.replace(/:/g,'$') #-> "a$a$$b$b$$c$c" better, but wrong we want '::' only
a.replace(/::/g,'$$') #-> "a:a$b:b$c:c" suprise; where is the 2nd Dollar?
a.replace("::",'$$') #-> "a:a$b:b::c:c" try no regexp since dollar has an other meaning? fails only one $
a.replace(/::/g,'\$\$') #-> "a:a$b:b$c:c" ESC the guys? nope
a.replace(/::/g,"\\$\\$") #-> "a:a\$\$b:b\$\$c:c" ESC ESC to get into the deeper?
# and then replace(/\\\$/g,'$') ? overkill
a.replace(/::/g,'$$$') #-> "a:a$$b:b$$c:c" bingo, but why?
# trying more
a.replace(/::/g,'$$$$') #-> "a:a$$b:b$$c:c" 2 get one? one stays alone
a.replace(/::/g,'$$$$$') #-> "a:a$$$b:b$$$c:c" seems so
毕竟,这是逻辑(我想知道为什么我以前从未遇到过这个问题)。
所以我认为(我确信)“$$”转义为“$”,因为“$n”引用了匹配的组 - 但即使没有正则表达式?
最佳答案
即使您没有任何捕获组,也可以在替换字符串中使用 $
。 $&
指的是正则表达式匹配的所有内容,$`
指的是匹配之前的所有内容,$'
指的是匹配之后的所有内容匹配。因此 $
总是被特殊对待,而 $$
表示只是一个 $
。
关于javascript - 如果我想要 "$$$"(两美元)作为 Java-/coffescript- 中的替换字符串,为什么我需要 "$$"(三美元),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33922077/