Replace characters that do not match characters in the regular expression

I have this regex:

private static final String SPACE_PATH_REGEX ="[a-z|A-Z|0-9|\\/|\\-|\\_|\\+]+";

I check if my string matches this regular expression, and IF NOT, I want to replace all characters that are not here with "_".

I tried:

private static final String SPACE_PATH_REGEX_EXCLUDE =
        "[~a-z|A-Z|0-9|\\/|\\-|\\_|\\+]+";
if (myCompanyName.matches(SPACE_PATH_REGEX)) {
    myNewCompanySpaceName = myCompanyName;
} else{
    myNewCompanySpaceName = myCompanyName.replaceAll(
            SPACE_PATH_REGEX_EXCLUDE, "_");
}

but it doesn’t work ... therefore in the second regular expression the “~” does not seem to omit the following characters.

Any idea?

+5
source share
2 answers

You have a few problems in your regex (see Patternclass for rules):

  • | ( , |).
  • /, _ + .
  • - escape,
  • ~ ,
  • ^, .

matches(), replaceAll() , . ( ) , , (, , ).

+8

Try:

final String SPACE_PATH_REGEX_EXCLUDE = "[^\\w~/\\-+]";
String out = in.replaceAll(SPACE_PATH_REGEX_EXCLUDE, "_");

, | . . , , \w, " ", ( ), [A-Za-z0-9_].

, . Java, \\, . . , \n Java String, \\n - , \n .

:

, . , - , . [a-z] . [a\-z] a, - z. -[a-z], , . : .

+4

All Articles