Got more questions? Find advice on: ASP | SQL | XML | Windows
in Search
Welcome to RegexAdvice Sign in | Join | Help

Justin's Regex Blog

Thinking in Regex

An Algorithm has been prepared, I'm linking it into an article so you don't have to look at it if you don't want. It is a spoiler.

The final algorithm has quite a few special cases, but I've attempted to refactor the code and make it as small as possible.  For readability I've chosen to use [0-9] in place of \d.  You can easily change this out and use the more common \d.  Note that the algorithm is not fully optimizing and it doesn't necessarily make use of optional characters, so patterns such as 0 255 turn out to be 5 alternation group items in place of the 4 people commonly find and the 3 that is possible.

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 0 255
(25[0-5]|[0-9]|2[0-4][0-9]|[1-9][0-9]|1[0-9][0-9])

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 222 228
(22[2-8])

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 699 700
(700|699)

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 699 701
(699|70[01])

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 699 710
(710|699|70[0-9])

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 698 710
(710|69[89]|70[0-9])

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 7650 7710
(7710|765[0-9]|770[0-9]|76[6-9][0-9])

C:\Projects\CSharp\RegularExpressions\BuildRangeGroups>BuildRangeGroups 6998998 7000000
(7000000|699899[89]|6999[0-9][0-9][0-9])

Here is the code if you are eager to take a look.  Sample Algorithm for Regex Range Validation

Sponsor
Published Monday, May 24, 2004 11:33 PM by jrogers

Comments

 

TrackBack said:

May 25, 2004 3:52 AM
Anonymous comments are disabled