Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
 }
like image 949
brakebg Avatar asked Jan 18 '23 11:01

brakebg


2 Answers

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 = "[^&%$#@!~]+";

like image 92
Narendra Yadala Avatar answered Jan 24 '23 17:01

Narendra Yadala


i think you want this:

[^&%$##@!~]*
like image 38
Kent Avatar answered Jan 24 '23 18:01

Kent