Huy Vo Huy Vo - 2 months ago 12
Scala Question

How to match a string with quantifiers as literals?

Let say I have a string:

"....O RLY?.....WTF?"


And I want to match it with a pattern:

val pattern = "BOTH SAEM|O RLY?|YA RLY|NO WAI|OIC|WTF?|OMG|GTFO|OMGWTF".r


But it never captures the
?
in my string. So I change it to:

val pattern = "BOTH SAEM|O RLY\?|YA RLY|NO WAI|OIC|WTF\?|OMG|GTFO|OMGWTF".r


This time it raises
invalid escape character
error.

I'm a newbie in Regex and can't find a solution for this. Please help!

Answer

You need to escape the question mark twice:

val pattern = "BOTH SAEM|O RLY\\?|YA RLY|NO WAI|OIC|WTF\\?|OMG|GTFO|OMGWTF".r

The explanation here is that you want to feed \? into the regex engine, to tell it to treat the question mark as a literal. But you need to escape the backslash itself, so that Scala won't think you're trying to escape the question mark in the Scala code.

Comments