"hello, I have 65 dollars".replaceFirst("dollars", p) 当前结果是 -6ren">
gpt4 book ai didi

string - scala,字符串变量处理为字符串而不是正则表达式

转载 作者:行者123 更新时间:2023-12-01 11:45:18 25 4
gpt4 key购买 nike

是否可以做到无缝衔接?

 scala> val p = "$"
scala> "hello, I have 65 dollars".replaceFirst("dollars", p)

当前结果是

 java.lang.StringIndexOutOfBoundsException: String index out of range: 1
....

scala 2.10 中的预期结果:

 hello, I have 65 $

问题出在存储符号 $ 的变量 p 上,我需要将其作为字符串而不是正则表达式进行处理。

注意: 我无法修改(例如替换所有非字母符号)p 变量(仅限标准函数,例如 .toString)

注意 2: 给定的示例相当玩具示例。我希望有一个更通用的解决方案。 IE。变量 p 可以包含任何类型的内容(符号、数字、文本...),因此将“$”替换为“\\$”没有多大意义

(这是类似问题的改进版本:scala string, raw string)

最佳答案

Regex.quote 用于模式,将 quoteReplacement 用于替换字符串。 (这些只是调用 Pattern。)

scala> import util.matching._
import util.matching._

scala> "hello, I have 65 dollars".replaceFirst("dollars", Regex quoteReplacement p)
res7: String = hello, I have 65 $

scala> "dollars".r replaceFirstIn ("hello, I have 65 dollars", Regex quoteReplacement p)
res8: String = hello, I have 65 $

scala> "hello, I have 65 dollars".replaceAllLiterally("dollars", p) // quotes both
res9: String = hello, I have 65 $

关于string - scala,字符串变量处理为字符串而不是正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15899122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com