Theomax
Theomax

Reputation: 6792

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

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

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:
  • ) - grouping construct end (it forcesd ^ and $ anchors be applied to each of the alternatives above)
  • $ - end of string.

Upvotes: 4

pawel.panasewicz
pawel.panasewicz

Reputation: 1833

  • How about | operator between Test1 and [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.

In terms of MVC - it has nothing to do with regex.

Upvotes: 1

Related Questions