Scala 字符串,原始字符串 [英] scala string, raw string

查看:71
本文介绍了Scala 字符串,原始字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以这样做:

"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 中的预期结果:

The expected result in scala 2.10:

 hello, I have 65 $

问题在于符号 $,我需要将它作为字符串而不是正则表达式来处理.我试图将它放入 """raw"" 但没有任何帮助

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

推荐答案

您可以对美元符号进行双重转义:

You can either double escape the dollar sign:

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

或者使用 Scala 三重引号和单转义.

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.

编辑

我不确定您是否想要65 $"——$65"不是更好的格式吗?为此,您需要一个捕获组和一个反向引用

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""");

输出:

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

这篇关于Scala 字符串,原始字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆