正则表达式以匹配2位数字(以验证信用卡/借记卡发行号) [英] Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

查看:216
本文介绍了正则表达式以匹配2位数字(以验证信用卡/借记卡发行号)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式来匹配一个正好2个字符的字符串,并且这两个字符都必须在0到9之间.要匹配的字符串将来自ASP时的单行文本输入字段.NET MVC视图已呈现

I would like to use regex to match a string of exactly 2 characters, and both of those characters have to be between 0 and 9. The string to match against would be coming from a single-line text input field when an ASP.NET MVC view is rendered

到目前为止,我有正则表达式

So far, I have the regex

[0-9]{2}

以及以下示例字符串输入列表

and from the following list of example string inputs

  • 456
  • 55 44
  • 12
  • 456
  • 55 44
  • 12

当我应用正则表达式时,将返回以下匹配项

the following matches are returned when I apply the regex

  • 45
  • 55
    44
  • 12
  • 45
  • 55
    44
  • 12

所以,我有一半的解决方案....我实际上要强制执行的操作是该字符串也正好是2个字符长,因此从字符串列表中,唯一应该匹配的是

So, I have kind of half the solution....what I actually want to enforce is that the string is also exactly 2 characters long, so that from the list of strings, the only one that should be matched is

12

我是一名正则表达式的公认业余爱好者,仅用于验证ASP.NET MVC模型上的卡发行号,如下所示.

I am an admitted amateur at regular expressions and am just using this to validate a card issue number on an ASP.NET MVC model as below....

[Required]
[RegularExpression("[0-9]{2}")]
public string IssueNumber { get; set; }

我确定我要问的内容很简单,但是我找不到任何示例来限制长度作为匹配的一部分.

I'm sure that what i'm asking is quite simple but I wasn't able to find any examples that limited the length as part of the matching .

谢谢.

推荐答案

您可以使用行指示器的开始(^)和结束($):

You can use the start (^) and end ($) of line indicators:

^[0-9]{2}$

某些语言还具有允许您与整个字符串匹配的功能,就像使用find函数一样.与整个字符串匹配将使您的正则表达式可以替代上述内容.上面的正则表达式也可以使用,但是^$将是多余的.

Some language also have functions that allows you to match against an entire string, where-as you were using a find function. Matching against the entire string will make your regex work as an alternative to the above. The above regex will also work, but the ^ and $ will be redundant.

这篇关于正则表达式以匹配2位数字(以验证信用卡/借记卡发行号)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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