JavaScript 正则表达式 - 仅两个 [az] 后跟三个 [0-9]

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

JavaScript regular expression - two [a-z] followed by three [0-9] only

javascriptregexstringstring-matching

提问by Scott Brown

I've got a simple regular expression:

我有一个简单的正则表达式:

[A-z]{2}[0-9]{3})$/ginside the following:

[A-z]{2}[0-9]{3})$/g在以下内容中:

regForm.submit(function(){
  if ($.trim($('#new-usr').val()).match(/([A-z]{2}[0-9]{3})$/g)) {
    alert('No');
    return false;
  }
});

This is correctly reading that something like 'ab123'gives an alert and 'ab1234'doesn't. However, 'abc123'is still throwing the alert. I need it so it's only throwing the alert when it's just 2 letters followed by three numbers.

这是正确的阅读类似的东西'ab123'发出警报而'ab1234'没有。但是,'abc123'还是抛出了警报。我需要它,所以它只在只有 2 个字母后跟三个数字时才会发出警报。

回答by Vlad

Try /^[A-z]{2}[0-9]{3}$/ginstead.

试试吧/^[A-z]{2}[0-9]{3}$/g

You need to specify that the whole string needs to be matched. Otherwise you get the highlighted part matched: abc123.

您需要指定需要匹配整个字符串。否则,您将匹配突出显示的部分: a bc123

(I omitted the ()'s, because you don't really need the group.)

(我省略了()'s,因为您并不真正需要该组。)

BTW, are you sure that you want [A-z]and not just [A-Za-z]?

顺便说一句,你确定你想要[A-z]而不仅仅是[A-Za-z]吗?

回答by codaddict

The character class [A-z]is probably not what you need.

字符类[A-z]可能不是您需要的。

Why?

为什么?

The character class [A-z]matches some non-alphabetical characters like [, ]among others.

字符类[A-z]匹配一些非字母字符,例如[]等等。

JS fiddle linkto prove this.

JS小提琴链接来证明这一点。

This W3school tutorialrecommends it incorrectly.

这个 W3school 教程错误地推荐了它。

If you need only lowercase letters use [a-z]
If you need only uppercase letters use [A-Z]
If you need both use: [a-zA-Z]

如果您只需要使用小写字母[a-z]
如果您只[A-Z]
需要使用大写字母如果您需要同时使用:[a-zA-Z]

If you want to match a string if it has 2 letters followed by 3 digits anywherein the string, just remove the end anchor $from your pattern:

如果你想匹配一个字符串,如果它在字符串中的任何地方有 2 个字母后跟 3 个数字,只需$从模式中删除结束锚点:

[a-z]{2}[0-9]{3}

If you want to match a string if it has 2 letters followed by 3 digits and nothing elseuse both start anchor ^and end anchor $as

如果你想匹配一个字符串,如果它有 2 个字母后跟 3 个数字,没有别的,使用开始锚点^和结束锚点$作为

^[a-z]{2}[0-9]{3}$

回答by sh54

Alternatively you can use:

或者,您可以使用:

/\b([A-z]{2}[0-9]{3})\b/g

if your string contains multiple words and you are trying to match one word.

如果您的字符串包含多个单词并且您正在尝试匹配一个单词。