Carole asked me for a quick way to validate some barcode formats for a client. When the barcode is scanned on the device it may only accept a format which looks like this:
1 to 5 digits + "”.” + 6 digits
In other words, at least one but no more than 5 digits followed by a “.” followed by 6 digits.
The regular expression to validate this is:
\b\d{1,5}\.\d{6}$
This breaks down like this:
\b denotes the beginning of a word
d{1,5} means at least one but no more than 5 digits
$ means end of string.
Although I studied Computer Science at university it was many moons ago and I kinda always bunked the regex party. Regular expressions just seemed too hard and it was only when I read this 30 minute tutorial a few years ago that I realized how easy and powerful regular expression were, for some reason suddenly I could grok the whole regex deal. (age?)
They are super efficient (read fast) and if you ever need to pattern match or extract data look no further.
There is a cool utility called RegexBuddy which makes the whole process even easier. Not so much for RegexBuddy’s expression breakdown’s but more for the test environment.
Here’s the C# code:
1: // array of test strings
2: string[] aryValues = { "1.123456", "12.123456", "123.123456", "1234.123456", "12345.123456",
3: "123456.12345667", "1234567.12345667", "12345678.123456678" };
4:
5: foreach (string s in aryValues)
6: {
7:
8: if (Regex.IsMatch(s,@"\b\d{1,5}\.\d{6}$"))
9:
10: System.Diagnostics.Debug.WriteLine(string.Format("{0} is valid.", s));
11:
12: else
13:
14: System.Diagnostics.Debug.WriteLine(string.Format("{0} is NOT valid.", s));
15:
16: }
And the results…
1.123456 is valid.
12.123456 is valid.
123.123456 is valid.
1234.123456 is valid.
12345.123456 is valid.
123456.12345667 is NOT valid.
1234567.12345667 is NOT valid.
12345678.123456678 is NOT valid.
Posted
Nov 06 2008, 01:49 PM
by
DerekMitchell