3

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?

0

3 Answers 3

8

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)
Sign up to request clarification or add additional context in comments.

Comments

5

Try this

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

Comments

2

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.