Java replacing special characters
Simply use String#replace(CharSequence target, CharSequence replacement)
in your case to replace a given CharSequence
, as next:
special = special.replace("@$", "as");
Or use Pattern.quote(String s)
to convert your String
as a literal pattern String
, as next:
special = special.replaceAll(Pattern.quote("@$"), "as");
If you intend to do it very frequently, consider reusing the corresponding Pattern
instance (the class Pattern
is thread-safe which means that you can share instances of this class) to avoid compiling your regular expression at each call which has a price in term of performances.
So your code could be:
private static final Pattern PATTERN = Pattern.compile("@$", Pattern.LITERAL);
...
special = PATTERN.matcher(special).replaceAll("as");
Escape characters:-
String special = "Something @$ great @$ that.";
special = special.replaceAll("@\\$", "as");
System.out.println(special);
For Regular Expression, below 12 characters are reserved called as metacharacters. If you want to use any of these characters as a literal in a regex, you need to escape 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 {
references:- http://www.regular-expressions.info/characters.html
The method replaceAll accepts regex as a pattern to substitue: 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");