gpt4 book ai didi

regex - 如何在scala中截断一个单词后的字符串

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

鉴于以下字符串...

"localhost:9000/one/two/three"

我想截断它 two并得到
"localhost:9000/one/two"

我已经实现了方法 truncateBeforetruncateAfter像这样:
def truncateBefore(s: String, p: String) = {
s.substring(s.indexOf(p) + p.length, s.length)
}

def truncateAfter(s: String, p: String) = {
s.substring(0, s.indexOf(p) + p.length)
}

这些方法工作并返回预期结果:
scala> truncateAfter("localhost:9000/one/two/three", "two")
res1: String = "localhost:9000/one/two"

scala> truncateBefore("localhost:9000/one/two/three", "two")
res2: String = "/three"

有没有更好的方法在 Scala 中做到这一点?最好使用正则表达式?

最佳答案

使用 的一种选择正则表达式 :

val beforeAfter = "(^.*two)(.*)$".r

scala> val beforeAfter(after, before) = "localhost:9000/one/two/three"
after: String = localhost:9000/one/two
before: String = /three

使用 的另一种选择拆分 :
scala> "localhost:9000/one/two/three" split ("two")
res0: Array[java.lang.String] = Array(localhost:9000/one/, /three)

如果您没有一个字,这些不是 super 强大的解决方案 two在输入中,但您可以相应地处理它...

再使用 正则表达式 理解:
scala> val beforeAfter = "(^.*two)(.*)$".r
beforeAfter: scala.util.matching.Regex = (^.*two)(.*)$

scala> (for {
| matches <- beforeAfter.findAllIn("localhost:9000/one/two/three").matchData
| tokens <- matches.subgroups
| } yield tokens).toList
res0: List[String] = List(localhost:9000/one/two, /three)

如果没有找到匹配项,这是安全的:
scala> (for {
| match <- beforeAfter.findAllIn("localhost").matchData
| token <- match.subgroups
| } yield token).toList
res1: List[String] = List()

关于regex - 如何在scala中截断一个单词后的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22104238/

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