user3407267
user3407267

Reputation: 1634

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.

Upvotes: 5

Views: 11912

Answers (2)

Brian
Brian

Reputation: 20285

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

Upvotes: 6

nmat
nmat

Reputation: 7591

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("/*/*")

Upvotes: 7

Related Questions