Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Java - String .replaceAll to replace specific characters (regex)

I need to remove some specific "special" characters and replace them with empty string if they show up. I am currently having a problem with the regex, probably with the Java escaping. I can't put them all together, it just doesn't work, I tried a lot! T_T

Currently I am doing it one by one which is kinda silly, but for now at least it works, like that :

public static String filterSpecialCharacters(String string) {
    string = string.replaceAll("-", "");
    string = string.replaceAll("\\[", "");
    string = string.replaceAll("\\]", "");
    string = string.replaceAll("\\^", "");
    string = string.replaceAll("/", "");
    string = string.replaceAll(",", "");
    string = string.replaceAll("'", "");
    string = string.replaceAll("\\*", "");
    string = string.replaceAll(":", "");
    string = string.replaceAll("\\.", "");
    string = string.replaceAll("!", "");
    string = string.replaceAll(">", "");
    string = string.replaceAll("<", "");
    string = string.replaceAll("~", "");
    string = string.replaceAll("@", "");
    string = string.replaceAll("#", "");
    string = string.replaceAll("$", "");
    string = string.replaceAll("%", "");
    string = string.replaceAll("\\+", "");
    string = string.replaceAll("=", "");
    string = string.replaceAll("\\?", "");
    string = string.replaceAll("|", "");
    string = string.replaceAll("\"", "");
    string = string.replaceAll("\\\\", "");
    string = string.replaceAll("\\)", "");
    string = string.replaceAll("\\(", "");
    return string;
}

Those are all the character I need to remove:

- [ ] ^ / , ' * : . ! > < ~ @ # $ % + = ? | " \ ) (

I am clearly missing something, I can't figure out how to put it all in one line. Help?

like image 905
JozeRi Avatar asked Mar 20 '16 10:03

JozeRi


1 Answers

Use these codes

String REGEX = "YOUR_REGEX";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(yourString);
yourString = m.replaceAll("");

UPDATE :

Your REGEX looks something like

String REGEX = "-|\\[|\\]|\\^|\\/|,|'|\\*|\\:|\\.|!|>|<|\\~|@|#|\\$|%|\\+|=\\?|\\||\\\\|\\\\\\\\|\\)|\\(";

SAPMLE :

String yourString = "#My (name) -is @someth\ing"";
//Use Above codes
Log.d("yourString",yourString);

OUTPUT

enter image description here

like image 133
Shree Krishna Avatar answered Sep 24 '22 01:09

Shree Krishna