简体   繁体   中英

Why does this JavaScript Regex match an underscore?

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?

In your regex, you have written Az (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\-\.]+)$

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM