I want to create several rather complex regular expressions used by my Scala code that take advantage of the Pattern.COMMENTS flag? I want to do something vaguely like this:
val regex = """my
(complex|hideous) # either is appropriate
pattern
(might)? # optional
look like this
""".r
(With the .r at the end of the string giving me all of Scala's Regex goodness)
Unfortunately, using .r doesn't give me any way to tell the Regex to use java.util.regex.Pattern.COMMENTS. Is there an way to create a scala.util.matching.Regex that compiles its source string with comments turned on?
According to the documentation, you should be able to use inline modifiers:
val regex = """(?x)my
(complex|hideous) # either is appropriate
pattern
(might)? # optional
look like this
""".r
See also the Java doc for Regex comments.
With an inline modifier, you enable the option from the point on, where the inline modifier is written. If you use it at the start, it is valid for the whole regular expression.
Check also regular-expressions.info for a further explanation
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