0

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?

2
  • 1
    What does your regex do? What does String#matches do? Commented Sep 17, 2014 at 3:16
  • Note that [^chars] will match exactly one character that is not one of the [chars]. And also note that String#matches acts as if your regex is ^regex$ Commented Sep 17, 2014 at 3:19

5 Answers 5

4

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].

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

If I want include space beside alphabet and number, what is the correct regex for this case?
post some example strings.
ex: I want to allow "Stack over flow 1"
0

I think you just have to remove the not-operator. Here is the same example, only the variable is renamed:

invalidChars = "[^a-zA-Z0-9]" ;  
String key = "message";
if (key.matches(invalidChars)) {
  message = "Invalid key";
}

(However, the negated logic is not very readable.)

Comments

0

Try below Alphanumeric regex

"^[a-zA-Z0-9]$"

^ - Start of string

[a-zA-Z0-9] - multiple characters to include

$ - End of string

1 Comment

Doesn't it matches ""(empty string) and therefore is not meeting the requirements?
0

With validation use \A \z anchors instead of ^ $:

\\A[a-zA-Z0-9]+\\z

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.