简体   繁体   English

在Java中将包含“$”的字符串替换为“\\ $”

[英]Replace a String containing “$” with “\$” in Java

How can I do it? 我该怎么做? I made a research but I could not find a clear answer.I tried to use 我做了一个研究,但我找不到一个明确的答案。我试着用

pass = pass.replaceAll("$", "\\$");

but It does not work. 但它不起作用。

use 采用

pass = pass.replace("$", "\\$");

It will also replace all occurrences. 它也将取代所有事件。 See JavaDoc . 请参阅JavaDoc

If you prefer the hard way and want to use a regex, you need: 如果你喜欢艰难的方式并想使用正则表达式,你需要:

pass = pass.replaceAll("\\$", "\\\\\\$");

This can be simplified with Matcher.quoteReplacement() but still, only use replaceAll() when you need to replace something that matches a regular expression, and use replace() when you have to replace a literal sequence. 这可以通过Matcher.quoteReplacement()简化,但仍然只需要替换匹配正则表达式的东西时使用replaceAll() ,并在必须替换文字序列时使用replace()

The problem is that String.replaceAll uses regular expressions, where both \\ and $ have special meanings. 问题是String.replaceAll使用正则表达式,其中\\$都有特殊含义。 You don't want that as far as I can tell - you just want to replace the strings verbatim. 据我所知,你不想要它 - 你只想逐字替换字符串。 As such, you should use String.replace : 因此,您应该使用String.replace

pass = pass.replace("$", "\\$");

(Personally I think the fact that replaceAll uses regular expressions is a design mistake, but that's another matter.) (我个人认为replaceAll使用正则表达式这一事实是一个设计错误,但这是另一回事。)

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

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