javascript 从范围中排除某些字符 - javascript正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28271771/
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
Excluding some character from a range - javascript regular expression
提问by Saif
To validate only word simplest regex would be (I think)
仅验证单词最简单的正则表达式是(我认为)
/^\w+$/
I want to exclude digits and _
from this (as it accept aa10aa
and aa_aa now, I want to reject them)
我想从中排除数字_
(因为它aa10aa
现在接受和 aa_aa,我想拒绝它们)
I think it can be gained by
我认为它可以通过
/^[a-zA-z]+$/
which means I have to take a different approach other than the previous one.
这意味着我必须采取不同于前一种方法的方法。
but what if I want to exclude any character from this range
suppose I will not allow k
,K
,p
,P
or more.
但是如果我想从这个范围中排除任何字符,假设我不允许k
, K
, p
,P
或更多怎么办。
Is there a way to add an excluding list in the range without changing the range.?
有没有办法在不改变范围的情况下在范围内添加排除列表。?
回答by Avinash Raj
To exclude k
or p
from [a-zA-Z]
you need to use a negative lookahead assertion.
要排除k
或p
从[a-zA-Z]
您需要使用否定前瞻断言。
(?![kpKP])[a-zA-Z]+
Use anchors if necessary.
必要时使用锚点。
^(?:(?![kpKP])[a-zA-Z])+$
It checks for not of k
or p
before matching each character.
它检查不是k
或p
每个字符匹配之前。
OR
或者
^(?!.*[kpKP])[a-zA-Z]+$
It just excludes the lines which contains k
or p
and matches only those lines which contains only alphabets other than k
or p
.
它只是排除其中包含线k
或p
与只匹配那些只包含字母以外的其他线路k
或p
。
回答by vks
^(?!.*(?:p|k))[a-zA-Z]+$
This should do it.See demo.The negative lookahead will assert that matching word has no p
or k
.Use i
modifier as well.
这应该可以做到。参见演示。否定前瞻将断言匹配的单词也没有p
或k
.Usei
修饰符。
https://regex101.com/r/vD5iH9/31
https://regex101.com/r/vD5iH9/31
var re = /^(?!.*(?:p|k))[a-zA-Z]+$/gmi;
var str = 'One\nTwo\n\nFour\nFourp\nFourk';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}