如何从右边的分隔符拆分字符串?

时间:2013-04-02 02:30:18

标签: scala

如何用右边的分隔符拆分字符串?

e.g。

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?']

3 个答案:

答案 0 :(得分:16)

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

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)

答案 1 :(得分: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)

答案 2 :(得分: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?)