I've been trying to remove a specific character from an Array of Strings but continue to fail. The char is "$", I don't know what I'm doing wrong so hoping someone would be able to point to the right direction, my code:
for (int y = 0; y<possibleAnswers.length;y++) {
display = possibleAnswers[y].replaceAll("$", "");
System.out.println(display);
}
possibleAnswers contains 4 Strings, one of the 4 has a "$", I want to remove it before displaying it.
When I run the above code, the "$" is displayed, any ideas?
The problem with your code is that replaceAll()
expects a "regular expression". The $ character has a specific meaning when used in a regular expression. Therefore you have two options:
replaceAll()
; then you have to "escape the special character"; by using replaceAll("\\\\$", "")
, or "[$]" as others have pointed out. replace()
that doesn't expect a "regular expression pattern string". replaceAll()
accepts a regex, not just a character. When you say "$", you're not telling it to match the '$' character, but to match the ending position of the String or before a newline before the end of the String.
You need to escape the '$', so it knows to match just the character, and not treat it like it's special regex meaning.
Do this like: possibleAnswers[y].replaceAll("\\\\$", "");
Try
possibleAnswers[y].replaceAll("\\$", "");
escape the character because $
is a special character in regular expression and since replaceAll()
take regular expression the string you passed is unidentified.
You can also use replace()
which take string
possibleAnswers[y].replace("$", "");
IN your code the $
is keyword
in regex
for matching end of line
ie $. SO you will have to escape
it as below.
display = possibleAnswers[y].replaceAll("\\$", "");
Just use possibleAnswers[y].replace("$", ""); to remove "$" from string.
for (int y = 0; y < possibleAnswers.length; y++) {
display = possibleAnswers[y].replace("$", "");
System.out.println(display);
}
As suggested, I used replace method instead of replaceAll and it did the job. At the same time I learned to look at documentation for deeper understanding of such methods.
Thanks for all the help guys, truly appreciated.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.