4

I am trying to use following JavaScript RE to match the string where allowed characters are uppercase or lowercase letters, digits, hypens (-), and periods (.). The underscore "_" is not allowed:

pattern = /^([a-zA-z0-9\-\.]+)$/

But when I run the test in the Chrome console: pattern.test("_linux");

The result is true, but should be false according to our rules. What's the reason?

6
  • 3
    Typo A-z should be A-Z. Commented Aug 12, 2016 at 1:32
  • Note: . doesn't have to be escaped inside the character class. Commented Aug 12, 2016 at 1:59
  • 2
    read point 1 of section 2.1 from here Commented Aug 12, 2016 at 2:07
  • @FelixKling Seconded, and neither does - Commented Aug 12, 2016 at 2:11
  • in Page 149 from the book <JavaScript The Definitive Guide> 4th edition, "." has special meaning and it should be preceded with "\". But I tested in the Chrome it works correctly if you don't add "\". For the "-" it's not needed. For the convenience of the programmer, is it best to add "\" if you don't know whether it should add "\" or not? Commented Aug 12, 2016 at 16:43

1 Answer 1

9

In your regex, you have written A-z (with a lowercase z at the end). In the JavaScript regex engine, this translates to character codes 65 to 122 rather than the desired 65 to 90. And the underscore character is within this range (char code 95); see an ASCII chart. Change it to a capital Z, making your regex:

^([a-zA-Z0-9\-\.]+)$
Sign up to request clarification or add additional context in comments.

1 Comment

I made a careless mistake. Thank you a lot!

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.