I have a string that must be on the following format:
XXXX-XX-XXX-XXXX-XXXXXXXXXX-X
where X is an integer. The number of integers don't matter. I just need to make sure that the string:
what would be the easiest way to validate that?
Use a regular expression.
^\d[-0-9]+\d$
This assumes the string is at least three characters long.
Breakdown:
^ - match start of string
\d - match a digit
[ - start of character class containing:
- - a dash
0-9 - 0 to 9
] - end of character class
+ - match one or more of the previous
\d - match a digit
$ - match end of string
You can change the +
to *
to make 2 digit strings valid, and add an alternation to make 1 digit strings valid as well:
^(\d|\d[-0-9]*\d)$
Note: In .NET, \d
will match any Unicode digit (so, for example, Arabic digits will match) - if you don't want that, replace \d
with [0-9]
in every place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With