Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validate string based on a format

Tags:

string

c#

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:

  • starts and ends with an integer
  • contains only integers separated by dashes

what would be the easiest way to validate that?

like image 202
Diego Avatar asked May 17 '12 13:05

Diego


1 Answers

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.

like image 62
Oded Avatar answered Sep 16 '22 19:09

Oded