Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala pattern matching with regexp lookbehind operator

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.

like image 533
Francis Toth Avatar asked Mar 14 '23 07:03

Francis Toth


1 Answers

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

like image 86
Sean Vieira Avatar answered Mar 23 '23 23:03

Sean Vieira