微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

regex – 如何在scala中的单词后截断字符串

鉴于以下字符串……

"localhost:9000/one/two/three"

我想在单词二之后截断它并得到

"localhost:9000/one/two"

我已经实现了truncateBefore和truncateAfter方法,如下所示:

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","three")
res1: String = localhost:9000/one/two

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

在scala中有更好的方法吗?最好用正则表达式?

解决方法

在第一个字面之后拆分,没有太多的正则表达式(双关语).

scala> implicit class `split after`(val s: String) {
     | def splitAfter(p: String): (String,String) = {
     |   val r = (Regex quote p).r
     |   r findFirstMatchIn s map (m => (s.substring(0,m.end),m.after.toString)) getorElse (s,"")
     | }}
defined class split$u0020after

scala> "abcfoodeffooghi" splitAfter "foo"
res2: (String,String) = (abcfoo,deffooghi)

scala> "abc*def" splitAfter "*"
res3: (String,String) = (abc*,def)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐