加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 09:53:39 所属栏目:安全 来源:网络整理
导读:鉴于以下字符串…… "localhost:9000/one/two/three" 我想在单词二之后截断它并得到 "localhost:9000/one/two" 我已经实现了truncateBefore和truncateAfter方法,如下所示: def truncateBefore(s: String,p: String) = { s.substring(s.indexOf(p) + p.lengt
鉴于以下字符串……

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读