Home > Blockchain >  Custom Regex format for ######-##
Custom Regex format for ######-##

Time:09-15

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. Could someone help me out?

Thanks!

CodePudding user response:

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


Note: Those answers that have ^ and $ in them are referring to start-of-line and end-of-line. But your question did not include any instructions about the format only being found on a line by itself.

I would not rely on those answers.

CodePudding user response:

^\d{6}-\d{2}$ and ^\d{6}-\d{1}$

  • Related