Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy Extended Regex Syntax

I'm trying to follow the example of Documenting Regular Expressions in Groovy but can't get my own example to work. Here's an example that fails on regex1, but works on the compressed regex2

def line = "some.key=a value # with comment that is ignored"
def regex1 = '''(?x)        # enable extended patterns
               ^\\s*        # ignore starting whitespace
               ([^=#]+)     # capture key
               =            # literal
               ([^#]*)      # capture value'''
def regex2 = '''^\\s*([^=#]+)=([^#]*)'''
def pattern = ~regex1
def matcher = pattern.matcher(line)
for (i=0; i < matcher.getCount(); i++) {
    println matcher[i][0]
    println matcher[i][1]
    println matcher[i][2]
}

The error i'm getting is

Caught: java.util.regex.PatternSyntaxException: Unclosed character class near index 217`

which points to the final closing brace on the last match.

If i change regex2 and add (?x) to the start of the string, it too fails in same way.

What is the correct syntax is for adding the extended patterns in this case? The example on the linked site works fine, so I know it should be possible.

like image 748
Mark Fisher Avatar asked Sep 13 '25 05:09

Mark Fisher


1 Answers

It's because you have # characters in your regex.

This means the parser is ignoring the text after them on each line they occur, so your grouping selectors and charactor selectors are not closed properly..

Try:

def regex1 = $/(?x)        # enable extended patterns
               ^\s*        # ignore starting whitespace
               ([^=\#]+)   # capture key
               =           # literal
               ([^\#]*)    # capture value/$

(I switched it to dollar slash string, as then you don't need to escape your escape chars (so you get \s and \# rather than \\s and \\#)

like image 87
tim_yates Avatar answered Sep 15 '25 03:09

tim_yates