Java replaces special characters

I am trying to replace special characters in a file with a pattern with only special characters, but it does not work.

String special = "Something @$ great @$ that."; special = special.replaceAll("@$", "as"); 

However, when I run, I get the original string instead of the replaced string. What am I doing wrong?

+5
source share
6 answers

Just use String#replace(CharSequence target, CharSequence replacement) in your case to replace the given CharSequence as follows:

 special = special.replace("@$", "as"); 

Or use Pattern.quote(String s) to convert your String to a literal String , as shown below:

 special = special.replaceAll(Pattern.quote("@$"), "as"); 

If you intend to do this very often, consider reusing the appropriate instance of the Pattern (the Pattern class is thread safe, which means you can exchange instances of this class) to avoid compiling your regular expression on every call that has a deadline price.

So your code could be:

 private static final Pattern PATTERN = Pattern.compile("@$", Pattern.LITERAL); ... special = PATTERN.matcher(special).replaceAll("as"); 
+7
source

Escape Symbols: -

  String special = "Something @$ great @$ that."; special = special.replaceAll("@\\$", "as"); System.out.println(special); 

For regular expressions, below 12 characters are reserved as metacharacters. If you want to use any of these characters as a literal in a regular expression, you need to avoid them with a backslash.

 the backslash \ the caret ^ the dollar sign $ the period or dot . the vertical bar or pipe symbol | the question mark ? the asterisk or star * the plus sign + the opening parenthesis ( the closing parenthesis ) the opening square bracket [ and the opening curly brace { 

links: - http://www.regular-expressions.info/characters.html

+5
source

The replaceAll method accepts a regular expression as a wildcard: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String )

Try simply:

 special = special.replace("@$", "as"); 
+2
source
 String special = "Something @$ great @$ that."; System.out.println(special.replaceAll("[@][$]", "as")); 

it should be like that.

+1
source

Please note that the first parameter specified is not the string you want to replace. This is a regular expression. You can try to create a regular expression that matches the string that you want to replace on this site .

special = special.replaceAll("\\@\\$", "as"); will work as suggested by @Mritunjay

0
source
 special = special.replaceAll("\\W","as"); 

works with all special characters.

0
source

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


All Articles