Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a Scala Regex that is compiled using Java Pattern.COMMENTS?

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?

like image 534
Mickalot Avatar asked Aug 02 '26 23:08

Mickalot


1 Answers

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

like image 111
stema Avatar answered Aug 05 '26 22:08

stema