Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string by delimiter from the right?

Tags:

scala

How to split a string by a delimiter from the right?

e.g.

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

Python has a .rsplit() method which is what I'm after in Scala:

In [1]: "hello there how are you?".rsplit(" ", 1)
Out[1]: ['hello there how are', 'you?']
like image 930
gak Avatar asked Apr 02 '13 02:04

gak


People also ask

How do you separate a string from a delimiter?

You can use the split() method of String class from JDK to split a String based on a delimiter e.g. splitting a comma-separated String on a comma, breaking a pipe-delimited String on a pipe, or splitting a pipe-delimited String on a pipe.

How do you split a string to a list using a comma delimiter?

Use str. split() to convert a comma-separated string to a list. Call str. split(sep) with "," as sep to convert a comma-separated string into a list.

How do I split a text string?

You can split the data by using a common delimiter character. A delimiter character is usually a comma, tab, space, or semi-colon. This character separates each chunk of data within the text string. A big advantage of using a delimiter character is that it does not rely on fixed widths within the text.


2 Answers

I think the simplest solution is to search for the index position and then split based on that. For example:

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 remarked on lastIndexOf returning -1, that's perfectly fine with the solution:

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

scala> msg splitAt (msg lastIndexOf ' ')
res0: (String, String) = ("",AstringWithoutSpaces)
like image 169
Daniel C. Sobral Avatar answered Sep 28 '22 05:09

Daniel C. Sobral


You could use plain 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'll look ahead (?=) for a group of non-space ([^ ]) characters with at least 1 character length. Finally this space followed by such sequence has to be at the end of the string: $.

This solution wont break if there is only one token:

scala> "hello".split(LastSpace)
res1: Array[String] = Array(hello)
like image 38
om-nom-nom Avatar answered Sep 28 '22 05:09

om-nom-nom