String scala字符串,原始字符串
是否有可能做到:String scala字符串,原始字符串,string,scala,replace,String,Scala,Replace,是否有可能做到: "hello, I have 65 dollars".replaceFirst("65", "$") 目前的结果是 scala> "hello, I have 65 dollars".replaceFirst("dollars", "$") java.lang.StringIndexOutOfBoundsException: String index out of range: 1 .... scala 2.10中的预期结果: hello, I have 65
"hello, I have 65 dollars".replaceFirst("65", "$")
目前的结果是
scala> "hello, I have 65 dollars".replaceFirst("dollars", "$")
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
....
scala 2.10中的预期结果:
hello, I have 65 $
问题是符号$,我需要将其作为字符串而不是regexp处理。我试图将其放入或原始,但没有任何帮助首先,您必须避开美元字符,因为现在它被视为正则表达式的一部分: 更可能的情况是,您希望替换word:
scala> "hello, I have 65 dollars".replaceFirst("dollars", "\\$")
res1: String = hello, I have 65 $
首先,您必须转义美元字符,因为现在它被视为正则表达式的一部分: 更可能的情况是,您希望替换word:
scala> "hello, I have 65 dollars".replaceFirst("dollars", "\\$")
res1: String = hello, I have 65 $
您可以双转义美元符号:
"hello, I have 65 dollars".replaceFirst("dollars", "\\$")
或者使用Scala三重引号和单转义
"hello, I have 65 dollars".replaceFirst("dollars", """\$""")
无论哪种方法,您都需要以等于\$的字符串文字结束,以反斜杠转义美元
编辑
我不确定你想要65美元-65美元不是更好的格式吗?为此,您需要一个捕获组和一个反向引用
"hello, I have 65 dollars".replaceFirst("""(\d++)\s++dollars""","""\$$1""");
输出:
res3: java.lang.String = hello, I have $65
您可以双转义美元符号:
"hello, I have 65 dollars".replaceFirst("dollars", "\\$")
或者使用Scala三重引号和单转义
"hello, I have 65 dollars".replaceFirst("dollars", """\$""")
无论哪种方法,您都需要以等于\$的字符串文字结束,以反斜杠转义美元
编辑
我不确定你想要65美元-65美元不是更好的格式吗?为此,您需要一个捕获组和一个反向引用
"hello, I have 65 dollars".replaceFirst("""(\d++)\s++dollars""","""\$$1""");
输出:
res3: java.lang.String = hello, I have $65