How to split a line into a separator on the right?

How to split a line into a separator on the right?

eg.

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

Python has a method .rsplit()that I got after Scala:

In [1]: "hello there how are you?".rsplit(" ", 1)
Out[1]: ['hello there how are', 'you?']
+5
source share
3 answers

I think the easiest solution is to search for the index position and then split based on this. For instance:

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

And since someone noticed on lastIndexOfreturning -1, this does a great job of solving:

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

scala> msg splitAt (msg lastIndexOf ' ')
res0: (String, String) = ("",AstringWithoutSpaces)
+12
source

You can use simple old regular expressions:

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

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

(?=[^ ]+$)says that we will look forward ( ?=) for a group of non-spatial ( [^ ]) characters with a length of at least 1 character. Finally, this space, followed by a sequence, should be at the end of the line: $.

, :

scala> "hello".split(LastSpace)
res1: Array[String] = Array(hello)
+4
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?)
+1
source

All Articles