smeeb smeeb - 1 year ago 73
Scala Question

Extracting inner group with Scala regex

My Scala app is being given a string that may or may not contain the token "

" inside of it, where the asterisk represents any kind of text, chars, punctuation, etc. There will always only be 0 or 1 instances of "
" in this string, never more.

I need to detect if the given input string contains a "
" instance, and if it does, extract out whatever is inside the two parentheses. Hence, if my string contains "
", then the result would be a string with a value of "
", etc.

My best attempt so far:

val inputStr : String = "blah blah flimFlam(Joe) blah blah"

// Regex must be case-sensitive for "flimFlam" (not "FLIMFLAM", "flimflam", etc.)
val flimFlamRegex = ".*flimFlam\\(.*?\\)".r
val insideTheParens = flimFlamRegex.findFirstIn(inputStr)

Can anyone spot where I'm going awry?

Answer Source

Use pattern matching and regex extractor

val regex = ".*flimFlam\\((.*)\\).*".r

inputStr match { 
 case regex(x) => println(x)
 case _ => println("no match")

Scala REPL

scala> val inputStr : String = "blah blah flimFlam(Joe) blah blah"
inputStr: String = blah blah flimFlam(Joe) blah blah

scala> val regex = ".*flimFlam\\((.*)\\).*"
regex: String = .*flimFlam\((.*)\).*

scala> val regex = ".*flimFlam\\((.*)\\).*".r
regex: scala.util.matching.Regex = .*flimFlam\((.*)\).*

scala> inputStr match { case regex(x) => println(x); case _ => println("no match")}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download