I have this regex:
private static final String SPACE_PATH_REGEX ="[a-z|A-Z|0-9|\\/|\\-|\\_|\\+]+";
I check if my string matches this regex and IF NOT, i want to replace all characters which are not here, with “_”.
I’ve tried like:
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 does not work…, so in the 2nd regex “~” seems to not omit the following chars.
Any idea?
You have several problems in your regex (see the
Patternclass for the rules):|has no special meaning and should be removed without replacement in your case (unless you want your character class to include the literal|character)./,_and+inside a character class.-only needs to be escape if it’s not the last character~also has no special meaning in a character class it just represents itself^to negate the content of a character group.You can also skip the first
matches()check, as thereplaceAll()call will return an unmodified String if nothing matches anyway. Keeping it (and the second regular expression) only serves to introduces another place where bugs could hide (for example you could accidentally update one regex, but not the other).