0

I try to remove special characters from string but the point is only "?" still on the output string while the others was removed properly.

String[] special = {"\\*",";","_","=", "\\[", "\\]", ":", "\\?", "-", "\\.", 
"\\)", "\\(", "/", "!", "#", ",", "\"", "“", "”"};
    for (int i = 0; i < special.length; i++) {
        source = source.replaceAll(special[i], "");
    }

this is my string

https://file.io/JjiLhD

  • Duplicate of [this](https://stackoverflow.com/questions/13696461/replace-special-character-with-an-escape-preceded-special-character-in-java) SO question. – Jeroen Heier Jun 26 '17 at 03:53
  • Possible duplicate of [Replace special character with an escape preceded special character in Java](https://stackoverflow.com/questions/13696461/replace-special-character-with-an-escape-preceded-special-character-in-java) – Oleg Estekhin Jun 26 '17 at 03:55
  • I knows it's duplicate I know how replace work but I just wanna know why question mark still appear on my text why others was replaced properly – Pitipon Manaviboon Jun 26 '17 at 04:09
  • Because you are viewing it as improperly encoded string – OneCricketeer Jun 26 '17 at 04:27
  • 1
    You should make that *much* clearer in your question then - at the moment, your question *reads* as if you're asking how to do the replacement properly, rather than satisfying your curiosity about why it's not working with `replaceAll`. If it's just the latter, I'm sure you can provide a simpler [mcve] than your current question. – Jon Skeet Jun 26 '17 at 04:38

2 Answers2

4

You should use replace instead of replaceAll because replaceAll uses input regex

for (int i = 0; i < special.length; i++) {
        source = source.replace(special[i], "");
    }

replace is same function with replaceAll but different input

Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.

Viet
  • 3,349
  • 1
  • 16
  • 35
  • thanks for the answer but when i use replace it will do 1 time but replaceAll replace all of my context there's still "?" appears :( – Pitipon Manaviboon Jun 26 '17 at 04:08
  • 1
    No, `replace` did replaceAll task, you can try it, It is java naming issue, you can read javadoc about it – Viet Jun 26 '17 at 04:18
0

Try this for alphanumeric characters.

.replaceAll("[^a-zA-Z0-9]", ""));

and only alphabetical characters,

.replaceAll("[^a-zA-Z]", ""));
Hariharan G R
  • 539
  • 2
  • 9