3

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?

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhh...I saw the comment: You can use special pattern syntax constructs like (?idmsux-idmsux)¹ to switch various regex compilation options like CASE_INSENSITIVE or UNICODE_CASE. But I didn't know what the heck idmsux meant, and I didn't see the (?x) line. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.