如果字符串包含不在 RegEx 中的字符,则 Javascript RegEx 返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7958718/
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
Javascript RegEx to return if string contains characters that are NOT in the RegEx
提问by Luke Shaheen
I have a user created string. I am only allowing the characters A-Z, a-z, 0-9, -,
and _
我有一个用户创建的字符串。我只允许字符A-Z, a-z, 0-9, -,
和_
Using JavaScript, how can I test to see if the string contains characters that are NOT these? If the string contains characters that are not these, I want to alert the user that it is not allowed.
使用 JavaScript,如何测试字符串是否包含非这些字符?如果字符串包含不是这些字符,我想提醒用户这是不允许的。
What Javascript methods and RegEx patterns can I use to match this?
我可以使用哪些 Javascript 方法和 RegEx 模式来匹配它?
回答by Donut
You need to use a negated character class. Use the following pattern along with the match
function:
您需要使用否定字符类。将以下模式与match
函数一起使用:
[^A-Za-z0-9\-_]
Example:
例子:
var notValid = 'This text should not be valid?';
if (notValid.match(/[^A-Za-z0-9\-_]/))
alert('The text you entered is not valid.');
回答by Ray Toal
This one is straightforward:
这个很简单:
if (/[^\w\-]/.test(string)) {
alert("Unwanted character in input");
}
The idea is if the input contains even ONE disallowed character, you alert.
这个想法是,如果输入甚至包含一个不允许的字符,你就会发出警报。