正则表达式否定 [英] negation in regular expression
问题描述
我想在JavaScript中使用正则表达式来进行表单输入验证。
这是一个字符串,不应该有< ,>或我提到的任何特定的字符集。如果字符串没有那些字符,测试应该通过。
I want to use regular expression in JavaScript for form input validation. These is a string which should not have either < , > or any specific set of chars which I mention. The test should pass if the string don't have those chars.
那么如何在正则表达式中指定不要有字符。
So how can I specify in regular expression not to have a char.
示例:
stringX = "vijay<>@$%_"
我的目标是
- 字符串不应该包含'<','>'字符。
- 如果stringX没有这些字符,则测试应该返回true。
注意:
我能做到:
stringX = "vijay<>@$%_"
regExp=/[<>`]/;
if(!rexExp.test(stringX)) {
doSomthing()
}
但我不想要这个。
因为我会遇到一个小麻烦。
Because I will end up in a small trouble.
我有一个名为validate()的泛型函数
I have a generic function called validate()
function validate(stringX, regExp)
{
if(rexExp.test(stringX)) { // see there is no "!" in the condition.
return true;
}
}
假设我要验证2个字符串。
Let's say I want to validate 2 strings.
- 案例1:只有数字。我会使用regExp:/ ^ [\ d] * $ /
- 案例2:没有<,>。我会使用regExp:/ ^ [<>`] * $
因为我不想指定所有允许的字符。我想指定不允许的字符
。
- Case 1: having only digits. I would use regExp : /^[\d]*$/
- Case 2: not having <,> . I would use regExp: /^[<>`]*$ Since I don't want to specify all characters to be ALLOWED. I would like to specify the chars which are NOT ALLOWED.
但我的验证功能仅适用于案例1.
与案例2一样,我不会得到预期的结果。只有当string只有<,>,`chars时,Validate()才会给我真实。
But my validate function will work with only in the case 1. As in the case 2, I will not get the expected result. Validate() would give me true only if string has only <,>,` chars.
推荐答案
如果你对字符串中的任何其他字符都没问题,这将匹配所有没有字符串的字符串字符<,>和`:
If you are okay with literally any other characters being in the string, this will match all strings that don't have the characters <, >, and `:
regexp=/[^<>`]*/;
编辑:使用行开始/结束锚点修正表达式(感谢MizardX) :
corrected expression with line start/end anchors (thanks MizardX):
regexp=/^[^<>`]*$/;
这篇关于正则表达式否定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!