Q:

Java string validation

I'm finding a regular expression which adheres below rules.
Allowed Characters
Alphabet : a-z A-Z
Numbers : 0-9
I am using [^a-zA-Z0-9] but when call 
regex = "[^a-zA-Z0-9]" ;  
String key = "message";
    if (!key.matches(regex))
                message = "Invalid key";

system will show Invalid key, The key should be valid. Could you please help me?

A:

If you want to allow these characters [a-zA-Z0-9] you should not use  ^ since it negates what is inside the []. 
This expression [^a-zA-Z0-9] means anything that is not a-z A-Z or numbers : 0-9.
You may have seen the ^ being used outside the [] at the begging of a regular expression to indicate the begging string like ^[a-zA-Z0-9].

A:

The below regex would allow one or more alphanumeric characters,
^[A-Za-z0-9]+$

Your regex [^a-zA-Z0-9], matches a single character but not of a alphanumeric character. [^..] called negated character class which do the negation of chars which are  present inside that character  class. 
You don't need to give start or end anchors in the regex when it is passed to matches method. So [A-Za-z0-9]+ would be enough.
Explanation:

^ Anchor which denotes the start.
[A-Za-z0-9]+ , + repeats the preceding token [A-Za-z0-9] one or more times.
$ End of the line.

