Grails replaceAll With Captured Groups/Backreferences

In a Grails app, I found myself needing to do a regex search, save captured groups/backreferences (I’m not sure of the distinction between those terms), and replace them with new content, which includes those backreferences. But I was having trouble finding a way to do it.

I tried using $1 or \1, but whenever I did that, I got an error that it was an invalid captured group or backreference.

The solution I found was the following.


content = content.replaceAll( /(a*b)/,
{ full, word -> "${word}" } )

This takes every example of a*b in the string content (like ab, aaab, etc.), and puts an anchor tag around it.

Advertisements

One Response to Grails replaceAll With Captured Groups/Backreferences

  1. Andrew says:

    Thanks for sharing. The backreference token is $, but since $ means something for a gstring, you can use single quotes to get a regular string or escape the $.

    String s = "ab not this aaab or this"
    String s1 = s.replaceAll(/(a*b)/ 
        , {full, word -> "${word}"})
    String s2 = s.replaceAll(/(a*b)/ , '$1')
    String s3 = s.replaceAll(/(a*b)/ , "\$1")
    assert s1 == s2 && s2 == s3
    

    See near the bottom of this page:
    http://groovy.codehaus.org/Regular+Expressions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: