Turn that love/hate relationship with regular expressions into just love

To paraphrase a saying,

Some people have a problem, and immediately think “I know, I’ll use regular expressions!” – Now they have 2 problems.

Regular expressions are powerful, but their complexity is exponentially proportional to what you need to do with them. It is syntactically complex, and on top of that, the syntax can vary subtly between different platforms (javascript, C#, php, perl, etc).

Enter Verbal Expressions

Compare something like this:

string strRegex = @"^https?://(?=www\.)?[^ ]+$";
RegexOptions myRegexOptions = RegexOptions.Multiline;
Regex myRegex = new Regex(strRegex, myRegexOptions);

To this:

[TestMethod]
public void TestingIfWeHaveAValidURL()
{
// Create an example of how to test for correctly formed URLs
var verbEx = new VerbalExpressions()
.StartOfLine()
.Then( "http" )
.Maybe( "s" )
.Then( "://" )
.Maybe( "www." )
.AnythingBut( " " )
.EndOfLine();

// Create an example URL
var testMe = "https://www.google.com";

Assert.IsTrue(verbEx.Test( testMe ), "The URL is incorrect");

Console.WriteLine("We have a correct URL ");
}

If you’ve spent any time with regular expressions this should blow your mind.

Heck, this makes me actually want to create a situation where I can use regular expressions, and that’s saying something.

Leave a Reply