How to remove invalid characters from a string?

I don't know how to remove invalid characters from a string in Java. I am trying to delete all characters that are not numbers, letters or () []. How can i do this?

thank

+5
source share
6 answers
String foo = "this is a thing with & in it";
foo = foo.replaceAll("[^A-Za-z0-9()\\[\\]]", "");

Javadocs is your friend. Regular expressions are also your friend.

Edit:

This is a siad, it is only for the Latin alphabet; You can customize accordingly. \\wcan be used to a-zA-Zdenote a word symbol if it works for your case, although it does include _.

+12
source

Using Guava and almost certainly more efficient (and more readable) than regular expressions:

CharMatcher desired = CharMatcher.JAVA_DIGIT
  .or(CharMatcher.JAVA_LETTER)
  .or(CharMatcher.anyOf("()[]"))
  .precomputed(); // optional, may improve performance, YMMV
return desired.retainFrom(string);
+8

:

String s = "123abc&^%[]()";
s = s.replaceAll("[^A-Za-z0-9()\\[\\]]", "");
System.out.println(s);

"&^%" , s "123abc[]()".

+3

:

String s = "Test[]"
s = s.replaceAll("[");
s = s.replaceAll("]");
0

myString.replaceAll("[^\\w\\[\\]\\(\\)]", "");
replaceAll . , , (\\w) (\\[\\]\\(\\)])

0

String/Url , .

  public static String removeSpecialCharacters(String inputString){
        final String[] metaCharacters = {"../","\\..","\\~","~/","~"};
        String outputString="";
        for (int i = 0 ; i < metaCharacters.length ; i++){
            if(inputString.contains(metaCharacters[i])){
                outputString = inputString.replace(metaCharacters[i],"");
                inputString = outputString;
            }else{
                outputString = inputString;
            }
        }
        return outputString;
   }
0

All Articles