Escaping dollars groovy

↘锁芯ラ 提交于 2019-12-11 13:44:54

问题


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.


回答1:


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.




回答2:


Anyone who gets here might like to know another answer to this, if you want to use Groovy slashy strings:

myComparisonString ==~ /.*something costs [$]stuff.*/

I couldn't find another way of putting a $ in a slashy string, at least if the $ is to be followed by text. If, conversely, it is followed by a number (or presumably any non-letter), this will work:

myComparisonString ==~ /.*something costs \$100.*/

... the trouble being, of course, that the GString "compiler" (if that's its name) would recognise "$stuff" as an interpolated variable.



来源:https://stackoverflow.com/questions/43363455/escaping-dollars-groovy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!