I have a string that looks like this:
val s = "123 some address (Latitude 100, Longitude 500)"
I just want to grab the text inside of the brackets.
What would be a safe way to do this without getting index out of bounds errors?
I can do this:
s.substring(s.indexOf("(") 1) // and then remove the last character
The value will always be in the string, that is guaranteed.
Just looking for alternative ways to make this code seem very readable and obvious, and safe from throwing exceptions.
CodePudding user response:
How about dropWhile
:
scala> s.dropWhile(_ != '(').tail.takeWhile(_ != ')')
val res0: String = Latitude 100, Longitude 500
CodePudding user response:
I don't quite understand why you are excluding regex solutions. They are the perfect solution for this problem:
final val regex = raw"\(([^)]*)\)".r.unanchored
val coord = s match
case regex(coord) => coord
Alternatively, you could use a string pattern:
val coord = s match
case s"$_($coord)$_" => coord