简体   繁体   English

正则表达式匹配特定的字符串和数字值

[英]Regex to match on specific string and number values

I'm trying to create a regex that will allow a specific string only (Test1) for example or numeric values. 我正在尝试创建一个仅允许特定字符串(例如Test1)或数字值的正则表达式。 How would I do this? 我该怎么做? I have tried the following but it doesn't work and won't notice the string part. 我已经尝试了以下方法,但是它不起作用并且不会注意到字符串部分。 What am I doing wrong with this regex? 这个正则表达式我在做什么错?

^Test1[0-9]*$

I want to use it in an MVC model validation attribute: 我想在MVC模型验证属性中使用它:

  [RegularExpression("^Test1[0-9]*$", ErrorMessage = "The value must be numeric or be Test1.")]

Your pattern - ^Test1[0-9]*$ - matches an entire string with the following contents: Test1 followed with 0 or more digits. 您的模式^Test1[0-9]*$ -匹配具有以下内容的整个字符串: Test1后跟0或多个数字。

If you meant to match either Test1 or zero or more digits as a whole string, you need 如果您要匹配整个字符串中的Test1或零个或多个数字,则需要

^(Test1|[0-9]*)$

Details : 详细资料

  • ^ - start of string ^ -字符串的开头
  • ( - grouping construct start: ( - 分组构造开始:
    • Test1 - either Test1 Test1 - Test1
    • | - or (this is an alternation operator ) -或(这是一个交替运算符
    • [0-9]* - zero or more digits [0-9]* -零个或多个数字
  • ) - grouping construct end (it forcesd ^ and $ anchors be applied to each of the alternatives above) ) -将构造端分组(强制将^$锚应用于上述每个替代项)
  • $ - end of string. $ -字符串结尾。
  • How about | 怎么样| operator between Test1 and [0-9]* ? Test1[0-9]*之间的运算符?
  • How about replacing * with + - thanks to that empty strings won't be catched? 如何更换*+ -这要归功于空字符串不会被逮住?

Regex ^Test1|[0-9]+$ should match all Test1 , 123 , 0 , 12345 and so on. 正则表达式^Test1|[0-9]+$应该匹配所有测试1,123,0,12345等。

In terms of MVC - it has nothing to do with regex. 就MVC而言-与正则表达式无关。

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

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