Search code examples
regexgroovyplaceholder

Escaping dollars groovy


I'm having trouble escaping double dollars from a string to be used with regex functions pattern/matcher.

This is part of the String:

WHERE oid_2 = $$test$$ || oid_2 = $$test2$$

and this is the closest code I've tried to get near the solution:

List<String> strList = new ArrayList<String>();
Pattern pattern = Pattern.compile("\$\$.*?\$\$");
log.debug("PATTERN: "+pattern)
Matcher matcher = pattern.matcher(queryText);
while (matcher.find()) {
    strList.add(matcher.group());
}
log.debug(strList)

This is the debug output i get

- PATTERN: $$.*?$$
- []

So the pattern is actually right, but the placeholders are not found in the string.

As a test I've tried to replace "$$test$$" with "XXtestXX" and everything works perfectly. What am I missing? I've tried "/$" strings, "\\" but still have no solution.


Solution

  • Note that a $ in regex matches the end of the string. To use it as a literal $ symbol, you need to escape it with a literal backslash.

    You used "\$\$.*?\$\$" that got translated into a literal string like $$.*?$$ that matches 2 end of string positions, any 0+ chars as few as possible and then again 2 end of strings, which has little sense. You actually would need a backslash to first escape the $ that is used in Groovy to inject variables into a double quoted string literal, and then use 2 backslashes to define a literal backslash - "\\\$\\\$.*?\\\$\\\$".

    However, when you work with regex, slashy strings are quite helpful since all you need to escape a special char is a single backslash.

    Here is a sample code extracting all matches from the string you have in Groovy:

    def regex = /\$\$.*?\$\$/;
    def s = 'WHERE oid_2 = $$test$$ || oid_2 = $$test2$$'
    def m = s =~ regex
    (0..<m.count).each { print m[it] + '\n' }
    

    See the online demo.