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

gak*_*gak 10 scala

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

例如

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

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

In [1]: "hello there how are you?".rsplit(" ", 1)
Out[1]: ['hello there how are', 'you?']
Run Code Online (Sandbox Code Playgroud)

Dan*_*ral 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?")
Run Code Online (Sandbox Code Playgroud)

因为有人评论说lastIndexOf返回-1,所以解决方案完全没问题:

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

scala> msg splitAt (msg lastIndexOf ' ')
res0: (String, String) = ("",AstringWithoutSpaces)
Run Code Online (Sandbox Code Playgroud)

  • `lastIndexOf`可以返回`-1`. (5认同)
  • @huynhjl在这种情况下,`splitAt`将首先返回一个空字符串,然后返回原始字符串。 (2认同)

om-*_*nom 5

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

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

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

(?=[^ ]+$)说我们将向前看(?=)一组[^ ]至少有1个字符长度的非空格()字符.最后这个空格后跟这样的序列必须在字符串的末尾:$.

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

scala> "hello".split(LastSpace)
res1: Array[String] = Array(hello)
Run Code Online (Sandbox Code Playgroud)