简体   繁体   English

带有可选字符的5位数的正则表达式

[英]Regex for 5 digit number with optional characters

I am trying to create a regex to validate a field where the user can enter a 5 digit number with the option of adding a / followed by 3 letters. 我正在尝试创建一个正则表达式来验证一个字段,用户可以输入一个5位数字,并可以选择添加/后跟3个字母。 I have tried quite a few variations of the following code: 我已经尝试了以下代码的几个变体:

^(\d{5})+?([/]+[A-Z]{1,3})? 

But I just can't seem to get what I want. 但我似乎无法得到我想要的东西。

For instance l would like the user to either enter a 5 digit number such as 12345 with the option of adding a forward slash followed by any 3 letters such as 12345/WFE . 例如,我希望用户输入一个5位数字,例如12345 ,可以选择添加正斜杠,然后添加任意3个字母,如12345/WFE

You probably want: 你可能想要:

^\d{5}(?:/[A-Z]{3})?$

You might have to escape that forward slash depending on your regex flavor. 根据你的正则表达风味,你可能不得不逃避正斜杠。

Explanation: 说明:

  • ^ - start of string anchor ^ - 字符串锚点的开始
  • \\d{5} - 5 digits \\d{5} - 5位数
  • (?:/[AZ]{3}) - non-capturing group consisting of a literal / followed by 3 uppercase letters (depending on your needs you could consider making this a capturing group by removing the ?: ). (?:/[AZ]{3}) - 由文字/后跟3个大写字母组成的非捕获组(根据您的需要,您可以考虑通过删除?:将其设为捕获组 )。
  • ? - 0 or 1 of what precedes (in this case that's the non-capturing group directly above). - 前面的0或1(在这种情况下是直接在上面的非捕获组)。
  • $ - end of string anchor $ - 字符串锚的结束

All in all, the regex looks like this: 总而言之,正则表达式如下所示:

在此输入图像描述

你可以使用这个正则表达式

/^\d{5}(?:\/[a-zA-Z]{3})?$/
^\d{5}(?:/[A-Z]{3})?$

这是实践中(这是一个测试你的正则表达的好网站): http ://regexr.com?36h9m

^(\d{5})(\/[A-Z]{3})?

测试为rubular

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM