scala string, raw string

2019-07-27 16:30发布

问题:

Is it possible to do:

"hello, I have 65 dollars".replaceFirst("65", "$")

Current result is

 scala> "hello, I have 65 dollars".replaceFirst("dollars", "$")
 java.lang.StringIndexOutOfBoundsException: String index out of range: 1
 ....

The expected result in scala 2.10:

 hello, I have 65 $

Problem is with symbol $, I need to process it as string not regexp. I tried to put it into """, or raw"" but nothing helped

回答1:

You can either double escape the dollar sign:

"hello, I have 65 dollars".replaceFirst("dollars", "\\$")

Or use Scala triple quotes and single escape.

"hello, I have 65 dollars".replaceFirst("dollars", """\$""")

Either way to you need end up with a String literal equal to "\$" to escape the dollar with a backslash.

EDIT

I'm not sure that you want "65 $" - isn't "$65" a better format? For this you need a capture group and a backreference

"hello, I have 65 dollars".replaceFirst("""(\d++)\s++dollars""","""\$$1""");

Output:

res3: java.lang.String = hello, I have $65


回答2:

First, you have to escape dollar character because right now it is treated as a part of regex (end-of-the-string sign):

"hello, I have 65 dollars".replaceFirst("65", "\\$")
res0: String = hello, I have $ dollars

It is much more likely you wanted to replace "dollars" word:

scala> "hello, I have 65 dollars".replaceFirst("dollars", "\\$")
res1: String = hello, I have 65 $