逃避美元 [英] Escaping dollars groovy

查看:177
本文介绍了逃避美元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从字符串中转义双精度元以用于正则表达式功能模式/匹配器.

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

这是字符串的一部分:

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)

这是我得到的调试输出

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

所以模式实际上是正确的,但是在字符串中找不到占位符.

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

作为测试,我尝试将"$$ test $$"替换为"XXtestXX",并且一切正常.我想念什么?我已经尝试过"/$"字符串,"\\",但仍然没有解决方案.

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.

推荐答案

请注意,正则表达式中的$与字符串的末尾匹配.要将其用作文字$符号,您需要使用文字反斜杠对其进行转义.

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.

您使用的"\$\$.*?\$\$"转换为像$$.*?$$这样的文字字符串,该字符串与字符串位置的2个结尾匹配,任何0+个字符应尽可能少,然后再与2个字符串的结尾匹配,这没有什么意义.实际上,您实际上需要一个反斜杠来转义Groovy中用于将变量注入到双引号字符串文字中的$,然后使用2个反斜杠定义一个文字反斜杠-"\\\$\\\$.*?\\\$\\\$".

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.

这是一个示例代码,可从Groovy中的字符串中提取所有匹配项:

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' }

请参见在线演示.

这篇关于逃避美元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆