brakebg
brakebg

Reputation: 414

Java regex validating special chars

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

Answers (3)

Narendra Yadala
Narendra Yadala

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

smp7d
smp7d

Reputation: 5032

To match a valid input:

String REGEX = "[^&%$#@!~]*";

To match an invalid input:

String REGEX = ".*[&%$#@!~]+.*";

Upvotes: 2

Kent
Kent

Reputation: 195289

i think you want this:

[^&%$##@!~]*

Upvotes: 2

Related Questions