Grails replaceAll With Captured Groups/Backreferences

October 13, 2010

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.