Java string: replace the string containing the $ sign

How to replace String $1with Java? I tried this, but this does not replace it:

System.out.println(someHTMLCodeAsString.replaceAll("$1", "REPLACED"));
+3
source share
6 answers

The value of $ is interpreted as a regular expression, and not as a character (this means "end of line"). TrySystem.out.println(someHTMLCodeAsString.replaceAll("\\$1", "REPLACED"));

+6
source

to try

 System.out.println(someHTMLCodeAsString.replace("$1", "REPLACED"));
+3
source

Java API: " , () ($) , , , . Matcher.replaceAll. quoteReplacement (java.lang.String) , .

0

You have a bit and bits of answer. Peter Laurie is right. You need to avoid $ with a regular expression excerpt rather than an escape string, so double \.

System.out.println (someHTMLCodeAsString.replaceAll ("\\ $ 1", "REPLACED"));

0
source

Or, let the regex library process it for you:

someHTMLCodeAsString.replaceAll(Pattern.quote("$1"), "REPLACED")
0
source

You can simply use this method:

someHTMLCodeAsString.replaceAll("\\$1", "REPLACED").

Just replace all "$" with "REPLACED"!

0
source

Source: https://habr.com/ru/post/1782200/


All Articles