0

I try to check the str validation by /^$/.test() method, and want it to return false after discovering there is

str = "Abc0Z";                       //string to be tested

regex_pattern  = /[^0-9A-Z]/;        //if 0-9 and A-Z  were not found in string, 
                                    // .test() returns true
                                   //otherwise, returns false

if(regex_pattern.test(str)){

//do something

}else{

//do other things

 }

In the above example, it returns true even when 0-9 And A-Z are found, is that the syntax of /[^Reg]/ is not supported in the Javascript Reg.text(test_string) method?

Can someone explain the mechanism behind, so the method return true other than false?

Because of the failure,I try the following to obtain the same purpose:

str = "Abc0Z";                       //string to be tested

regex_pattern  = /[0-9A-Z]/;        //if 0-9 and A-Z  were found in string, .test() return true
                                    //otherwise, returns false

if(regex_pattern.test(str) == false){

//do something

}else{

//do other things

}

And it works as I want it to. But I really don't know why /[^0-9A-Z]/ is not work as expected...Is that any mistake of my Regex syntax or any other reasons to make it work unsuccessful?

Thanks for any help!

vincentat
  • 11
  • 1
  • 2

3 Answers3

0

Use start and end patterns in your regex and also add case insensitive i modifier,

/^[^0-9A-Z]+$/i

DEMO

Now for this Abc0Z input, it returns false.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You forgot small letters: try with /[^0-9A-Za-z]/ expression.

Nebril
  • 3,153
  • 1
  • 33
  • 50
-1

The ^ inside the character class ([^…]) negates only the character class, not the entire pattern. In other words, /[^0-9A-Z]/ doesn't return true if not 0-9 or A-Z are not found in the string. It returns true if at least one of any character other than 0-9 and A-Z are found in the string.

If you want a pattern that will return true if it does not contain any character in a particular character class, use start and end anchors (^ and $) and a zero-or more quantifier (*) like this:

/^[^0-9A-Z]*$/.test(str)

Or simply take your original pattern and negate the results

!/[0-9A-Z]/.test(str)

Also, remember you can use the case insensitive (i) if you want to match upper and lower case letters:

!/[0-9A-Z]/i.test(str)
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331