正则表达式匹配一个2位数字(以验证信用卡/借记卡发行号)

时间:2022-05-31 17:14:18

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

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

So far, I have the regex

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

[0-9]{2}

and from the following list of example string inputs

并从以下示例字符串输入列表中

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

the following matches are returned when I apply the regex

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

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

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

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

12

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....

我是正则表达式的业余爱好者,我只是用它来验证ASP.NET MVC模型上的卡片发行号,如下所示....

[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 .

我确信我所要求的是非常简单但我无法找到任何限制长度的例子作为匹配的一部分。

Thanks, in advance.

提前致谢。

3 个解决方案

#1


36  

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

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

^[0-9]{2}$

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


10  

You need to use anchors to match the beginning of the string ^ and the end of the string $

您需要使用锚点来匹配字符串^的开头和字符串$的结尾

^[0-9]{2}$

#3


1  

Something like this would work

像这样的东西会起作用

/^\d{2}$/

#1


36  

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

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

^[0-9]{2}$

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


10  

You need to use anchors to match the beginning of the string ^ and the end of the string $

您需要使用锚点来匹配字符串^的开头和字符串$的结尾

^[0-9]{2}$

#3


1  

Something like this would work

像这样的东西会起作用

/^\d{2}$/