javascript 正则表达式测试是否只有 ASCII 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18017862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:28:42  来源:igfitidea点击:

Regex to test if only ASCII characters

javascriptregex

提问by Sami

I have tried this but it returns true for both UTF-8 and ASCII:

我试过这个,但它对于 UTF-8 和 ASCII 都返回 true:

 console.log(/[^w/]+/.test("abc123")) //true
 console.log(/[^w/]+/.test("???")) //true

回答by SmokeyPHP

I think you meant /[^\w]+/but what you really want, from what I can gather, is:

我想你的意思是,/[^\w]+/但你真正想要的是,据我所知,是:

console.log(/^[\x00-\x7F]+$/.test("abc123")) //true
console.log(/^[\x00-\x7F]+$/.test("abc_-8+")) //true
console.log(/^[\x00-\x7F]+$/.test("???")) //false

If you didn't actually mean to check the full ASCII set, you can just use:

如果您实际上并不是要检查完整的 ASCII 集,则可以使用:

console.log(/^[\w]+$/.test("abc123")) //true
console.log(/^[\w]+$/.test("abc_-8+")) //false
console.log(/^[\w]+$/.test("???")) //false

About \x notation

关于 \x 符号

\xFFis a hexadecimal notation (list here) used in this example for the range 00to 7Fto match the full ASCII character set. \x00-\x7Fis functionally indentical to a-zin that it specifies a range, however we are using hex notation for reliable ranging

\xFF是一个十六进制表示法(名单这里在本例中使用的范围内)00,以7F相匹配的完整的ASCII字符集。\x00-\x7F功能相同a-z,因为它指定了一个范围,但是我们使用十六进制表示法来实现可靠的范围

\wmatches 'word' characters, which is the same as [a-z0-9_]

\w匹配 'word' 字符,这与 [a-z0-9_]