Reputation: 4699
I have a sequence of strings like these:
val foo = Seq("bar scala baz", "bar java baz", "bar python baz")
I need to extract everything between bar
and baz
such that I get something like this:
val foobarbaz = Seq("scala", "java", "python")
How do I do this using regular expressions in Scala?
Upvotes: 3
Views: 8498
Reputation: 61656
Starting Scala 2.13
, it's possible to pattern match a String
s by unapplying a string interpolator:
// val foo = Seq("bar scala baz", "bar java baz", "bar python baz")
foo.map { case s"bar $lang baz" => lang }
// List("scala", "java", "python")
Upvotes: 2
Reputation: 20405
Not necessarily with regular expressions, consider String
strip methods, like this,
foo.map { _.stripPrefix("bar").stripSuffix("baz").trim }
res: Seq[String] = List(scala, java, python)
Upvotes: 8
Reputation: 2431
Try this
val regex = "^bar(.*)baz$".r
val foobarbaz = foo.collect { case regex(a) => a.trim }
Upvotes: 5