Javascript 正则表达式正好匹配 4 位数字

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

RegEx match exactly 4 digits

javascriptregex

提问by Moritz Büttner

Ok, i have a regex pattern like this /^([SW])\w+([0-9]{4})$/

好的,我有一个这样的正则表达式模式 /^([SW])\w+([0-9]{4})$/

This pattern should match a string like SW0001with SW-Prefix and 4 digits.

这种模式应该与像绳子SW0001SW-前缀和4位。

I thougth [0-9]{4}would do the job, but it also matches strings with 5 digits and so on.

[0-9]{4}想会做这项工作,但它也匹配 5 位数字等的字符串。

Any suggestions on how to get this to work to only match strings with SWand 4 digits?

关于如何使其工作以仅匹配SW4 位数字的字符串的任何建议?

回答by Tushar

Let's see what the regex /^([SW])\w+([0-9]{4})$/match

让我们看看正则表达式/^([SW])\w+([0-9]{4})$/匹配什么

  1. Start with S or W since character class is used
  2. One or more alphanumeric character or underscore(\w= [a-zA-Z0-9_])
  3. Four digits
  1. 以 S 或 W 开头,因为使用了字符类
  2. 一个或多个字母数字字符或下划线 ( \w= [a-zA-Z0-9_])
  3. 四位数

This match more than just SW0001.

这场比赛不止SW0001

Use the below regex.

使用下面的正则表达式。

/^SW\d{4}$/

This regex will match string that starts with SWfollowed by exactly four digits.

此正则表达式将匹配以 开头SW后跟四位数字的字符串。

回答by Jerome WAGNER

in regex,

在正则表达式中,

  • ^means you want to match the start of the string
  • $means you want to match the end of the string
  • ^意味着你想匹配字符串的开头
  • $意味着你想匹配字符串的结尾

so if you want to match "SW" + exactly 4 digits you need

所以如果你想匹配“SW”+你需要的4位数字

^SW[0-9]{4}$