Project Description
Adds a validation wrapper around regular expressions, allowing you to automatically apply conditional logic to capture groups.

The concept of this project is this: a regular expression basically encapsulates one of the beginning stages of the compilation process. Namely lexical analysis. I'm wanting to expand the capabilities of the regular expression parser to take on a higher compilation stage, roughly equivalent to semantic analysis. Hence the project name. You will note that there aren't any classes in this library called SemanticEx. It's just too wordy.

I created this project to solve the problem of how unmaintainable real-world regular expressions are. Take the problem of matching a valid IP address; you have the following regular expression:

^(?<first>\d{1,3})\.(?<remainder>\d{1,3})\.(?<remainder>\d{1,3})\.(?<remainder>\d{1,3})$


This works, except that there is no easy way to constrain the "first" group to 1-->255, and the "remainder" groups to 0-->255. You could write a 10-line regular expression that will match on the allowed decimal numbers, or with this library you could write the following:

var regex = new Regex(@"^(?<first>\d{1,3})\.(?<remainder>\d{1,3})\.(?<remainder>\d{1,3})\.(?<remainder>\d{1,3})$")
	.Validate("(1 <= first)&&(255 >= first)")
	.Validate("(0<=remainder) && (255>=remainder)");

var match = regex.Match("127.0.0.1234");
Console.WriteLine("Non-home check: {0}", match.Success);
match = regex.Match("256.a.0.1");
Console.WriteLine("Non-home check: {0}", match.Success);
match = regex.Match("127.0.0.401");
Console.WriteLine("Non-home check: {0}", match.Success);
match = regex.Match("127.0.0.1");
Console.WriteLine("Non-home check: {0}", match.Success);
match = regex.Match("192.168.1.1");
Console.WriteLine("Non-home check: {0}", match.Success);


Additionally, if you wanted to match IP addresses that start with the number 127, you could wrap the original regex variable like so:

var homeCheck = regex.Validate("first => first==127");

Console.WriteLine("Home check: {0}", homeCheck.Match("127.0.0.1").Success);
Console.WriteLine("Home check: {0}", homeCheck.Match("254.268.0.1").Success);
Console.WriteLine("Home check: {0}", homeCheck.Match("192.168.0.0").Success);


The original regex validators still work, plus you have a new homeCheck validator to further filter your inputs.

There is also support for creating validators from lambda expressions. Look around the code for details on how everything works, especially the RegexExtensions class. Check out the two test classes in SemanticEx.Tests for examples of how to use the library.

I'm sharing a lot of the code for this project with my XEnamel project. You should check that one out too if you like dynamic expressions.

Last edited Aug 17, 2010 at 9:59 PM by treytomes, version 6