Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I extract substring (group) using regex without knowing if regex matches?

Tags:

I want to use this

val r = """^myprefix:(.*)""".r
val r(suffix) = line
println(suffix)

But it gives an error when the string doesn't match. How do I use a similar construct where matching is optional?

Edit: To make it clear, I need the group (.*)

like image 427
User Avatar asked Aug 04 '12 17:08

User


2 Answers

You can extract match groups via pattern matching.

val r = """^myprefix:(.*)""".r
line match {
  case r(group) => group
  case _ => ""
}

Another way using Option:

Option(line) collect { case r(group) => group }
like image 104
Kim Stebel Avatar answered Oct 16 '22 17:10

Kim Stebel


"""^myprefix:(.*)""".r        // Regex
  .findFirstMatchIn(line)     // Option[Match]
  .map(_ group 1)             // Option[String]

This has the advantage that you can write it as a one-liner without needing to assign the regex to an intermediate value r.

In case you're wondering, group 0 is the matched string while group 1 etc are the capture groups.

like image 35
Luigi Plinge Avatar answered Oct 16 '22 19:10

Luigi Plinge