javascript 正则表达式只检查大写字母、两个特殊字符(& 和 ?)& 之间没有任何空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3977268/
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-25 02:52:25  来源:igfitidea点击:

Regex to check only capital letters, two special characters (& and ?) & without any space between

javascriptregexstring

提问by Biki

I am using below code snippet to validate my input string with: only capital letters, numbers and two special characters (those are & and ?) & without any space between.

我使用下面的代码片段来验证我的输入字符串:只有大写字母、数字和两个特殊字符(那些是 & 和?)& 之间没有任何空格。

var validpattern = new RegExp('[^A-Z0-9\d&?]');
if (enteredID.match(validpattern))
   isvalidChars = true;
else
   isvalidChars = false;

Test 1: "XAXX0101%&&$#"should fail i.e isvalidChars = false;(as it contains invalid characters like %$#.

测试 1:"XAXX0101%&&$#"应该失败 ie isvalidChars = false;(因为它包含无效字符,如%$#.

Test 2: "XAXX0101&?3?&"should pass.

测试2:"XAXX0101&?3?&"应该通过。

Test 3: "XA 87B"should fail as it contains space in between

测试 3:"XA 87B"应该失败,因为它之间包含空格

The above code is not working, Can any one help me rectifying the above regex.

上面的代码不起作用,任何人都可以帮我纠正上面的正则表达式。

回答by codaddict

This is happening because you have a negation(^) insidethe character class.

发生这种情况是因为你有一个否定(^的字符类。

What you want is: ^[A-Z0-9&?]+$or ^[A-Z\d&?]+$

你想要的是: ^[A-Z0-9&?]+$^[A-Z\d&?]+$

Changes made:

所做的更改:

  • [0-9]is same as \d. So use either of them, not both, although it's not incorrect to use both, it's redundant.
  • Added start anchor (^) and end anchor($) to match the entirestring not partof it.
  • Added a quantifier +, as the character class matches a singlecharacter.
  • [0-9]与 相同\d。所以使用它们中的一个,而不是两个,虽然两者都使用并没有错,但它是多余的。
  • 添加了开始锚点 ( ^) 和结束锚点 ( $) 以匹配整个字符串而不是它的一部分
  • 添加了量词+,因为字符类匹配单个字符。

回答by N 1.1

^[A-Z\d&?]+$

0-9not required.

0-9不需要。

回答by ghostdog74

if you want valid patterns, then you should remove the ^in the character range.

如果你想要有效的模式,那么你应该删除^字符范围内的 。

[A-Z0-9\d&?]

[A-Z0-9\d&?]

回答by Biki

Using jquery we could achieve the same in one line:

使用 jquery 我们可以在一行中实现相同的效果:

$('#txtId').alphanumeric({ allow: " &?" });

Using regex (as pointed by codaddict) we can achieve the same by

使用正则表达式(如 codacci 所指出的)我们可以通过

var validpattern = new RegExp('^[A-Z0-9&?]+$');

Thanks everyone for the precious response added.

感谢大家的宝贵回复。