10

如何从右侧通过分隔符拆分字符串?

例如

scala> "hello there how are you?".rightSplit(" ", 1)
res0: Array[java.lang.String] = Array(hello there how are, you?)

Python 有一个.rsplit()方法,这是我在 Scala 中所追求的:

In [1]: "hello there how are you?".rsplit(" ", 1)
Out[1]: ['hello there how are', 'you?']
4

3 回答 3

17

我认为最简单的解决方案是搜索索引位置,然后根据它进行拆分。例如:

scala> val msg = "hello there how are you?"
msg: String = hello there how are you?

scala> msg splitAt (msg lastIndexOf ' ')
res1: (String, String) = (hello there how are," you?")

并且由于有人评论lastIndexOf返回-1,因此解决方案非常好:

scala> val msg = "AstringWithoutSpaces"
msg: String = AstringWithoutSpaces

scala> msg splitAt (msg lastIndexOf ' ')
res0: (String, String) = ("",AstringWithoutSpaces)
于 2013-04-02T03:02:30.183 回答
5

您可以使用普通的旧正则表达式:

scala> val LastSpace = " (?=[^ ]+$)"
LastSpace: String = " (?=[^ ]+$)"

scala> "hello there how are you?".split(LastSpace)
res0: Array[String] = Array(hello there how are, you?)

(?=[^ ]+$)表示我们将提前 ( ) 查找一组至少有 1 个字符长度?=的非空格 ( ) 字符。[^ ]最后,这个空格后面跟着这样的序列必须在字符串的末尾:$.

如果只有一个令牌,此解决方案不会中断:

scala> "hello".split(LastSpace)
res1: Array[String] = Array(hello)
于 2013-04-02T08:42:42.373 回答
1
scala> val sl = "hello there how are you?".split(" ").reverse.toList
sl: List[String] = List(you?, are, how, there, hello)

scala> val sr = (sl.head :: (sl.tail.reverse.mkString(" ") :: Nil)).reverse
sr: List[String] = List(hello there how are, you?)
于 2013-04-02T19:37:54.410 回答