如何在Groovy中找到带有美元符号的双引号字符串的子字符串 [英] How to find a substring of a double-quoted string with a dollar sign in Groovy

查看:374
本文介绍了如何在Groovy中找到带有美元符号的双引号字符串的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想纠正自动创建的Linux脚本。我使用 findAll(String,String)函数将$ APP_ARGS更改为其他内容。 b
$ b

我已经尝试过变种:

$ p $ replaceAll('$ APP_ARGS','模拟器'+'\\\ $ APP_ARGS') - 找不到
replaceAll('\\ $ APP_ARGS \',... - 找不到
replaceAll('\ $ APP_ARGS',... - 没有找到
replaceAll('\\\\ $ APP_ARGS \\'',... - 编辑器警告 - 过度转义
replaceAll('\\\\\ $ APP_ARGS',... - 没有找到
replaceAll('\\\\ \\\ $ APP_ARGS\\\\\'',... - 找不到
replaceAll($ /$$ APP_ARGS/ $,...) - 找不到
replaceAll('[$] APP_ARGS','something simple') - 找到
replaceAll('[$] APP_ARGS','\\\\ \ $ APP_ARGS') - 失败。

正如你所看到的,如果我使用正则表达式格式,发现工作正常,但有没有办法逃避工作?因为我需要 $ 在替换字符串中。

根据Groovy手册,/../字符串不需要转义,除了斜杠。但是

  replaceAll(/$ APP_ARGS/,... 

也会失败,并显示一条消息:Could not get unknown property'APP_ARGS'。



那个函数的行为没有任何逻辑,我们必须通过实验找到正确的解决方案。

解决方案

  replaceAll(''\\ $ APP_ARGS','simulators'+'\\ $ APP_ARGS')

另外可能的问题是在 $ 之前的 \\ 应该是在这两个字符串中,替换和替换。

replaceAll 的第一个参数总是被当作正则表达式,所以我们需要引用 $ (行结束)。第二个参数可能包含对regexp组的反向引用,它们以 $

更好的方法是使用替换来代替,这样就必须引用一个。 code>更换所有,它们已经根据用法引用/转义了两个参数。


I wanted to correct the automatically created Linux scripts. I use findAll(String, String) function to change "$APP_ARGS" for something else.

I have tried variants:

replaceAll('"$APP_ARGS"', 'simulators ' + '"\\\\$APP_ARGS"')    - doesn't find
replaceAll('\"\$APP_ARGS\"',...    - doesn't find
replaceAll('"\$APP_ARGS"',...    - doesn't find
replaceAll('\\"\\$APP_ARGS\\"',...    - editor warning - excessive escape
replaceAll('"\\\\$APP_ARGS"',...    - doesn't find
replaceAll('\\\\"\\\\$APP_ARGS\\\\"',...    - doesn't find
replaceAll($/"$$APP_ARGS"/$, ...)   - does not find
replaceAll('"[$]APP_ARGS"', 'something simple')       - finds.
replaceAll('"[$]APP_ARGS"', '"\\\\$APP_ARGS"')       - fails.

As you see, if I use the regex format, the finding works ok. But is there a way to make an escaping work? For I need that $ in the replacing string, too.

According to Groovy manuals, /../ string needn't escaping for anything except slashes themselves. But

 replaceAll(/"$APP_ARGS"/,... 

fails, too, with a message: Could not get unknown property 'APP_ARGS'.

It seems that behaviour of that function has no logic and we have to find the correct solution by experiments.

解决方案

replaceAll('"\\$APP_ARGS"', 'simulators ' + '"\\$APP_ARGS"')

The additional possible problem is that \\ before $ should be in the both strings, replacing and replaced.

The first argument of replaceAll is always treated as an regexp, so we need to quote $ (line end). The second param may contain backreferences to groups from the regexp, which start with a $, so that one must be quoted too.

A saner way is to use replace instead of replaceAll, which already quotes/escapes both params according to that useage.

这篇关于如何在Groovy中找到带有美元符号的双引号字符串的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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