RegEx正好匹配4位数 [英] RegEx match exactly 4 digits

查看:94
本文介绍了RegEx正好匹配4位数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有一个像这样的正则表达式模式 / ^([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 和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


  1. 从S或W开始使用字符类

  2. 一个或多个字母数字字符或下划线( \w = [a-zA -Z0-9 _]

  3. 四位数

  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

这匹配的不仅仅是 SW0001

使用以下正则表达式。

/^SW\d{4}$/

这个正则表达式会匹配以 SW 开头的字符串,后跟恰好四位数字。

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

这篇关于RegEx正好匹配4位数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆