简体   繁体   English

在Java中转义$的最优雅方法

[英]most elegant way of escaping $ in java

I have a base String "abc def" , I am trying to replace my base string with "abc$ def$" using replaceFirst() , which is running into errors as $ is not escaped. 我有一个基本字符串"abc def" ,我正在尝试使用replaceFirst()将我的基本字符串替换为"abc$ def$" ,因为$不能转义,这会replaceFirst()错误。

I tried doing it with Pattern and Matcher APIs, as given below, 我尝试使用Pattern和Matcher API做到这一点,如下所示,

newValue = "abc$ def$";

if(newValue.contains("$")){
    Pattern specialCharacters = Pattern.compile("$");
    Matcher newMatcherValue = specialCharacters.matcher(newValue) ;
    newValue = newMatcherValue.replaceAll("\\\\$") ;
}

This runs into an error. 这会出错。 Is there any elegant way of replacing my second string "abc$ def$" with "abc\\\\\\\\$ def\\\\\\\\$" so as to use the replacefirst() API successfully? 有什么优雅的方法可以将我的第二个字符串"abc$ def$"替换为"abc\\\\\\\\$ def\\\\\\\\$"以便成功使用replacefirst() API?

Look at Pattern.quote() to quote a regex and Matcher.quoteReplacement() to quote a replacement string. 查看Pattern.quote()引用正则表达式, Matcher.quoteReplacement()引用替换字符串。

That said, does this do what you want it to? 就是说,这是您想要的吗?

System.out.println("abc def".replaceAll("([\\w]+)\\b", "$1\\$"));

This prints out abc$ def$ 打印出abc$ def$

You can use replaceAll just in one step: 您只需一步即可使用replaceAll:

String newValueScaped = newValue.replaceAll("\\$", "\\\\$")

$ has a special mining in regex, so you need to scape it. $在正则表达式中有一个特殊的挖掘,因此您需要对其进行处理。 It's used to match the end of the data. 它用于匹配数据的结尾。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM