Reputation: 414
This seems like a well known title, but I am really facing a problem in this.
Here is what I have and what I've done so far.
I have validate input string, these chars are not allowed :
&%$##@!~
So I coded it like this:
String REGEX = "^[&%$##@!~]";
String username= "jhgjhgjh.#";
Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(username);
if (matcher.matches()) {
System.out.println("matched");
}
Upvotes: 4
Views: 13197
Reputation: 9664
Change your first line of code like this
String REGEX = "[^&%$#@!~]*";
And it should work fine. ^
outside the character class denotes start of line. ^
inside a character class []
means a negation of the characters inside the character class. And, if you don't want to match empty usernames, then use this regex
String REGEX = "[^&%$#@!~]+";
Upvotes: 5
Reputation: 5032
To match a valid input:
String REGEX = "[^&%$#@!~]*";
To match an invalid input:
String REGEX = ".*[&%$#@!~]+.*";
Upvotes: 2