Francis Toth
Francis Toth

Reputation: 1685

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.

Upvotes: 4

Views: 1066

Answers (1)

Sean Vieira
Sean Vieira

Reputation: 160025

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

Upvotes: 7

Related Questions