Reputation: 6792
I'm trying to create a regex that will allow a specific string only (Test1) for example or numeric values. 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:
[RegularExpression("^Test1[0-9]*$", ErrorMessage = "The value must be numeric or be Test1.")]
Upvotes: 5
Views: 11953
Reputation: 626835
Your pattern - ^Test1[0-9]*$
- matches an entire string with the following contents: Test1
followed with 0 or more digits.
If you meant to match either Test1
or zero or more digits as a whole string, you need
^(Test1|[0-9]*)$
Details:
^
- start of string(
- grouping construct start:
Test1
- either Test1
|
- or (this is an alternation operator)[0-9]*
- zero or more digits)
- grouping construct end (it forcesd ^
and $
anchors be applied to each of the alternatives above)$
- end of string.Upvotes: 4
Reputation: 1833
|
operator between Test1
and [0-9]*
?*
with +
- thanks to that empty strings won't be catched?Regex ^Test1|[0-9]+$
should match all Test1, 123, 0, 12345 and so on.
In terms of MVC - it has nothing to do with regex.
Upvotes: 1