5

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.")]
8
  • Did you mean to write ^(Test1|[0-9]*)$? To match Test1 or zero or more digits? Commented Sep 21, 2016 at 14:55
  • 1
    (Test1) for example or numeric values => ^(?:Test1|[0-9]+)$ Commented Sep 21, 2016 at 14:55
  • ^Test1|\d+$ will match "Test1" or any numeric value. Commented Sep 21, 2016 at 14:56
  • No unless you enclose branches in parentheses. @ThePerplexedOne Commented Sep 21, 2016 at 14:57
  • @revo What? OP isn't asking to capture any groups. My expression is fine. Commented Sep 21, 2016 at 14:58

2 Answers 2

4

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the detailed answer - how would I modify your suggestion to specify the number of digits must be 4? I tried the following but it doesn't work: ^Test1|[0-9]{4}+$
Use ^(Test1|[0-9]{4})$. Do not forget the parentheses, they are crucial here. Else, you'd need to repeat the anchors in every branch: ^Test1$|^[0-9]{4}$.
@WiktorStribiżew thanks for the detailed answer. It helped me solve more problems.
1
  • 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.

2 Comments

Agreed it is not related to MVC just wanted to add abit more context to the question :)
^Test1|[0-9]+$ also finds a match in Test1$%^&^%$## and _______________________________-5.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.