-4

I am absolutely clueless when it comes to Regex strings. I am trying to create a custom validator on a model using [RegularExpression("myValidator")] How can I create a regex expression to validate the following formats

  • ######-##
  • ######-#

where # is a number.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Selthien
  • 1,178
  • 9
  • 33

1 Answers1

0
  • \d means digit.
  • {N} means previous symbol repeated N times

so, basically you want:

\d{6}-\d{2}

which would match 6 digits, a dash, and 2 more digits.

You can also do:

\d{6}-\d{1,2}

which would match 6 digits, a dash, and then 1 or 2 more digits, and therefore work for either format you described.

abelenky
  • 63,815
  • 23
  • 109
  • 159
  • Did you read the question? Your answer says nothing about `######-#`... – NetMage Sep 14 '22 at 19:16
  • 1
    If the OP cannot figure out `######-#` from the info I provided, they have issues.... – abelenky Sep 14 '22 at 19:17
  • Note that `^` and `$` refer to start and end of string, not line, unless you are using the multiline option. Since the original question referred to a validator for a model, this is presumably for a single string field, in which case accepting e.g. ABC######-# would be incorrect, so the `^` and `$` are needed. – NetMage Sep 14 '22 at 19:31