4

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.

1 Answer 1

5

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 \\#)

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

3 Comments

Didn't know about the Dollar Slashy strings. Great!
bah, of course. thanks, couldn't see the wood for the trees. nice tip on the slashy strings too.
@MarkFisher No worries, took me a while to see where it was going wrong ;-)

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.