Pitipon Manaviboon
Pitipon Manaviboon

Reputation: 9

Why my replaceAll not work

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

Upvotes: 0

Views: 135

Answers (2)

Hariharan G R
Hariharan G R

Reputation: 549

Try this for alphanumeric characters.

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

and only alphabetical characters,

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

Upvotes: 0

Viet
Viet

Reputation: 3409

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.

Upvotes: 4

Related Questions