I'm trying to extract a value from a String using a regexp and pattern matching :
val reg = """((?<=a)b)""".r
"ab" match { case reg(x) => x }
No matter how I try, it still throws a MatchError. However, if I try the following method :
reg.findAllIn("ab").mkString
The regex behaves as expected : res28: String = b
Of course, I could simply change the regex and add another group :
val reg = """(a)(b)""".r
"ab" match { case reg(_,x) => x }
but I'm wondering if it's possible to use look ahead/behind operators with pattern matching.
Thank you in advance.
Yes, but in a pattern match you don't get a call to Matcher.find
, as you do in Regex.findAllIn
, so you have to turn it into an UnAnchoredRegex
by using Regex.unanchored
(or match everything in the first go):
val reg = "((?<=a)b)".r.unanchored
// ".*((?<=a)b)".r would also work
"ab" match { case reg(x) => x }
The key entry in the ScalaDoc is:
This method attempts to match the entire input by default; to find the next matching subsequence, use an unanchored Regex.
(emphasis mine).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With