Blankman
Blankman

Reputation: 266920

What is a safe way to extract a value from a string without using regex

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.

Upvotes: 0

Views: 75

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369428

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

Scastie link

Upvotes: 4

esse
esse

Reputation: 1551

How about dropWhile:

scala> s.dropWhile(_ != '(').tail.takeWhile(_ != ')')
val res0: String = Latitude 100, Longitude 500

Upvotes: 2

Related Questions