Reputation: 938
I have a string like that ($
character is always surrounded with other characters):
a$b
c$d
e$f
I want my string method to put a \
in front of $
and remove newlines:
a\$bc\$de\$f
I tried this but it doesn't put \
character:
s=s.replaceAll("\n","").replaceAll("$", "\\$");
Upvotes: 6
Views: 215
Reputation: 41223
Your issue here is that '$' is a regular expression metacharacter. That is, it has special meaning. Specifically, '$' means 'end of string'.
Since you don't have any metacharacters in your pattern, you can instead use String.replace()
, which just replaces literal strings.
s = s.replace("$","\\$");
However, if you really want to use replaceAll()
(for example if other parts of your pattern need to be metacharacters):
If you want to match an actual '$', you need to escape the '$' in the pattern to make it a literal '$'.
\$
Then you also need to escape the '\' for Java's quoting, so you end up with:
s = s.replaceAll("\\$","\\$");
However, '$' is still a metacharacter in the second parameter, so we need more:
s = s.replaceAll("\\$",Matcher.quoteReplacement("\\$"));
Together with your other replacement:
s = s.replaceAll("\\$",Matcher.quoteReplacement("\\$")).replaceAll("\n","");
Upvotes: 2
Reputation: 2826
Use replace()
method instead of replaceAll()
. As Michelle correctly notes, replaceAll()
uses regular expressions, that cause problems with $
character, while replace()
is literal, which is quite sufficient for your case.
Upvotes: 8
Reputation: 43013
Escape $
like this:
s=s.replaceAll("\n","").replaceAll("\\$", "\\\\\\$");
$
is a metacharacter for the first argument of the replaceAll
method.
This first argument is a regular expression. From a regular expression point of view, $
means end of line or string.
String s = "a$b\n" +
"c$d\n" +
"e$f\n";
s = s.replaceAll("\n", "").replaceAll("\\$", "\\\\\\$");
System.out.println(s);
a\$bc\$de\$f
Upvotes: 2
Reputation: 5414
S
and \
are special characters :
s = s.replaceAll("\n", "").replaceAll("\\$", "\\\\\\$");
Upvotes: 0
Reputation: 48404
$
is a reserved character in java Pattern
s, it indicates the end of line or end of input.
You also need to escape the replacement... thrice.
Try replaceAll("\\$", "\\\\\\$")
Upvotes: 5