My issues is to allow only a-z, A-Z, 0-9, points, dashes and underscores and [] for a given string.
Here is my code but not working so far.
[a-zA-Z0-9._-]* this one works ok for validating a-z, A-Z, 0-9 points, dashes and underscores and but when it comes to add and [] i got error Illegal character.
[a-zA-Z0-9._-\\[]]*
it’s obviously that [] broke the regex.
Any suggestion how to handle this proble?
String REGEX = "[a-zA-Z0-9._-\\[]]*";
String username = "dsfsdf_12";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(username);
if (matcher.matches()) {
System.out.println("matched");
} else {
System.out.println("NOT matched");
}
You have to escape both [] as shown below: