Core_Dumped
Core_Dumped

Reputation: 4699

Extract string between two strings in Scala

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

Answers (3)

Xavier Guihot
Xavier Guihot

Reputation: 61656

Starting Scala 2.13, it's possible to pattern match a Strings 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

elm
elm

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

tiran
tiran

Reputation: 2431

Try this

val regex = "^bar(.*)baz$".r
val foobarbaz = foo.collect { case regex(a) => a.trim }

Upvotes: 5

Related Questions