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

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

Excluding some character from a range - javascript regular expression

javascriptregex

提问by Saif

To validate only word simplest regex would be (I think)

仅验证单词最简单的正则表达式是(我认为)

/^\w+$/

I want to exclude digits and _from this (as it accept aa10aaand 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,Por 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 kor pfrom [a-zA-Z]you need to use a negative lookahead assertion.

要排除kp[a-zA-Z]您需要使用否定前瞻断言。

(?![kpKP])[a-zA-Z]+

Use anchors if necessary.

必要时使用锚点。

^(?:(?![kpKP])[a-zA-Z])+$

It checks for not of kor pbefore matching each character.

它检查不是kp每个字符匹配之前。

OR

或者

^(?!.*[kpKP])[a-zA-Z]+$

It just excludes the lines which contains kor pand matches only those lines which contains only alphabets other than kor p.

它只是排除其中包含线kp与只匹配那些只包含字母以外的其他线路kp

DEMO

演示

回答by vks

^(?!.*(?:p|k))[a-zA-Z]+$

This should do it.See demo.The negative lookahead will assert that matching word has no por k.Use imodifier as well.

这应该可以做到。参见演示。否定前瞻将断言匹配的单词也没有pk.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.
}