RegEx正好匹配4位数 [英] RegEx match exactly 4 digits
问题描述
好的,我有一个像这样的正则表达式模式 / ^([SW])\ w +([0-9] {4})$ /
Ok, i have a regex pattern like this /^([SW])\w+([0-9]{4})$/
此模式应与 SW0001
之类的字符串匹配 SW
-Prefix和4位数。
This pattern should match a string like SW0001
with SW
-Prefix and 4 digits.
我想要 [0-9] {4}
会做这个工作,但它也是匹配5位数的字符串,依此类推。
I thougth [0-9]{4}
would do the job, but it also matches strings with 5 digits and so on.
有关如何使其工作的建议仅匹配 SW $ c $的字符串c>和4位?
Any suggestions on how to get this to work to only match strings with SW
and 4 digits?
推荐答案
让我们看看正则表达式 / ^([SW])\\ \\ w +([0-9] {4})$ /
匹配
Let's see what the regex /^([SW])\w+([0-9]{4})$/
match
- 从S或W开始使用字符类
- 一个或多个字母数字字符或下划线(
\w
=[a-zA -Z0-9 _]
) - 四位数
- Start with S or W since character class is used
- One or more alphanumeric character or underscore(
\w
=[a-zA-Z0-9_]
) - Four digits
这匹配的不仅仅是 SW0001
。
使用以下正则表达式。
/^SW\d{4}$/
这个正则表达式会匹配以 SW
开头的字符串,后跟恰好四位数字。
This regex will match string that starts with SW
followed by exactly four digits.
这篇关于RegEx正好匹配4位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!