开发者

replaceFirst in Groovy throws Illegal group reference

I have the following code:

String newStr = "aa\$";
print newStr;
print "wwwww ? eeee".replaceFirst("\\?", "'${newStr}'"); // (3)

and I keep getting -- at line 3 -- the following error:

Caught: java.lang.IllegalArgumentException: Illegal group reference
    at com.example.MyBuilder.main(MyBuilder.groovy:196)

It looks like that 开发者_开发知识库replaceFirst ignores that $ was escaped. How could I let my code run? Does anybody experience such an error?


First

String newStr == "aa\$"

should be

String newStr = "aa\$"

Then, because you are using normal strings to declare your regex, you need to double escape the dollar sign:

String newStr = "aa\\$"

Or, use slashy strings:

String newStr = /aa\$/


I have found a working solution for my problem: String newStr == "aa\\\$"; You need to have three backslashes. The first backslash (from right to left) escapes $ so Groovy Interpreter does not understand $ as a mark for a variable.

The two following slashes has to escape $ for replaceFirst, because $ is interpreted by Matcher.appendReplacement() -- called inside replaceFirst -- as a grouping. It is an unexpected but well documented in JavaDoc behavior:

backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string

ps. After fighting with escaping other "special" symbol -- backslash -- I switched to String.replace(CharSequence,CharSequence).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜