Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get substring in scala?

How do I get the substring for the string :

 "s3n://bucket/test/files/*/*"

I would like to get s3n://bucket/test/files alone. I tried the split :

"s3n://bucket/test/files/*/*".split("/*/*") but this gives me array of strings with each character.

like image 695
user3407267 Avatar asked Feb 09 '17 00:02

user3407267


People also ask

What is substring in sql?

SQL Server SUBSTRING() Function The SUBSTRING() function extracts some characters from a string.

What is Scala take?

In Scala Stack class , the take() method is utilized to return a stack consisting of the first 'n' elements of the stack. Method Definition: def take(n: Int): Stack[A] Return Type: It returns a stack consisting of the first 'n' elements of the stack.


2 Answers

The argument to split is a regex and /*/* matches all the characters in your string. You need to escape *:

"s3n://bucket/test/files/*/*".split("/\\*/\\*")

An alternative to split in this case could be:

"s3n://bucket/test/files/*/*".stripSuffix("/*/*")
like image 80
nmat Avatar answered Oct 14 '22 06:10

nmat


A couple of options not using a regex.

Using takeWhile gives "s3n://bucket/test/files/" which includes the last slash.

scala> s.takeWhile(_ != '*')
res11: String = s3n://bucket/test/files/

Using indexOf to find the first "*" and taking one less character than that gives the output you specify.

scala> s.slice(0,s.indexOf("*") - 1)
res14: String = s3n://bucket/test/files
like image 24
Brian Avatar answered Oct 14 '22 07:10

Brian