Tag Archives: Regex

NOSQL, NoRM (mongoDB) and Regular Expressions

Over the past few weeks I have got quite involved in the development of the Open Source NoRM project started by Andrew Theken which is a MongoDB driver for C#. In particular I have been refactoring and adding new functionality to the LINQ provider.

It currently supports a lot of functionality including deep queries, regex, datetime which is really exciting. In this post though I am going to concentrate on regular expressions.

This is the newest part of the Linq provider however it is probably the most powerful, especially for complex queries. The reason for this is that MongoDB will use the indexes created when a regular expression is used (where the query is not a complex query). A complex query is one that filters on the same property twice, uses a string function (replace/substring/toLower etc) or does some other fancy stuff. For example using the toUpper() method.

var products = session.Products.Where(x => x.Name.ToUpper() == "TEST3").ToList();

Anyways….i digress. So, here is an example of using a Regex in a Linq Query. Pretty simple.

var products = session.Products.Where(p => Regex.IsMatch(p.Name, "^te")).ToList();

Using the static Regex.IsMatch is the only way to invoke a regex call using the Linq Provider. This will however run blazingly fast. I tested this query on 1,000,000 Products and it only took 1.5sec, which was approximately 10x faster than when a complex query is invoked. There are however 3 string functions that have been optimized using this regex functionality. They are StartsWith(), EndsWith() and Contains() which is why the following query only takes 2secs to return over 48,000 rows, however when using Skip() and Take() you can get 50 results back in just milliseconds.

var products = session.Products.Where(x => x.Name.StartsWith("X")).ToList();

The Linq provider also supports 3 of the RegexOptions. They are RegexOptions.IgnoreCase (but please note this will not use the index so will be slower), RegexOptions.Multiline and RegexOptions.None. Regex’s can also be used in conjunction with other filters. eg.

var products = session.Products.Where(p => Regex.IsMatch(p.Name, "^te") && p.Price == 10).ToList();

This query is not considered a complex query because two different properties are used and an “and”(&&) operator is used.

Please note: Any time a “or” (||) operator is used, it will be considered a complex query.

Summary:

If you have a filter than can be written as a regex, chances are it will be as fast or faster than without using a regex.

So please go and try out NoRM and enjoy the freedom. I will try and post some more cool stuff in the LINQ provider over the next few weeks. Stay tuned.

Linq and Regular Expressions

With Linq now standard in .NET 3.5, there is no reason why we shouldn’t use it. After all its full of features that can be used by any object that inherits the type IEnumberable. With such power at our fingertips, sorting, filtering, manipulation etc. etc. are available to us with fewer lines of code than previous needed.

One powerful feature of programing is Regular Expressions. These provide a concise and flexible means for identifying text of interest, such as particular characters, words, or patterns of characters. So whilst going over some old code of mine to extract data from a remote website, I decided to give the Regular Expression part of my code a face lift with Linq.

The code below is the setup code just to give some background.

String StringToMatch = "<tr class=\"ar1\"><td>456642</td>"
        + "<td class=\"left\">John</td>"
        + "<td class=\"left\">Smith</td>"
        + "<td>j.smith@email.com</td></tr>"
        + "<tr class=\"ar1\"><td>456643</td>"
        + "<td class=\"left\">Edward</td>"
        + "<td class=\"left\">Norman</td>"
        + "<td>e.norman@email.com</td></tr>";

Regex r = new Regex("<tr class=\"(?:ar1|ar2)\"><td>([0-9]+)</td>"
        + "<td class=\"left\">(.*?)</td>"
        + "<td class=\"left\">(.*?)</td>"
        + "<td>(.*?)</td></tr>");

MatchCollection matches = r.Matches(StringToMatch);

The following code is the preLinq version of the code to process the Regular Expression.

List<Profile> Profiles = new List<Profile>();

if (matches.Count > 0)
{
    foreach (Match m in matches)
    {
        Profile p = new Profile();

        p.Id = m.Groups[1].Value;
        p.Firstname = m.Groups[2].Value;
        p.Lastname = m.Groups[3].Value;
        p.Email = m.Groups[4].Value;

        Profiles.Add(p);
    }
}

As you can see above, a strongly typed List of type Profile is created. Then we loop through each match, first creating a new instance of the Profile object. Filling the object up with the results from our Regular Expression and finally adding it to the list. Whilst this code is pretty straight forward, look how easily Linq handles this scenario.

if (matches.Count > 0)
{
     List<Profile> Profiles = (from Match m in matches
                              select new Profile
                              {
                                  Id = m.Groups[1].Value,
                                  Firstname = m.Groups[2].Value,
                                  Lastname = m.Groups[3].Value,
                                  Email = m.Groups[4].Value
                              }).ToList();
}

As you can see above, we have managed to reduced the amount of statements from around 8 to 1. So what this is doing in english is creating a strongly typed List of the type Profile and using Linq to fill it. It states that for ever Match m in the list matches, create a new object Profile and auto initialise the variables with the values contained in the match. Finally we convert the IEnumberable<Profile> result to a List<Profile> by using the method ToList().

How easy was that! Now say you wanted the list of Profile’s sorted by lastname. Well you would normally have to build the list as above and then call the Sort method using a defined Comparison object. This is where Linq becomes even more powerful. Simply by adding one line to the Linq statement above, the List generated will be sorted by lastname.

if (matches.Count > 0)
{
     List<Profile> Profiles = (from Match m in matches
                       --->   orderby m.Groups[3].Value
                              select new Profile
                              {
                                  Id = m.Groups[1].Value,
                                  Firstname = m.Groups[2].Value,
                                  Lastname = m.Groups[3].Value,
                                  Email = m.Groups[4].Value
                              }).ToList();
}

Also another point to add regarding the definition of class Profile. Back in .NET 2.0 days creating a class was pretty painful. A lot of repeated code just to get and object with some variables.

public class Profile
{
    private string _id;
    private string _firstname;
    private string _lastname;
    private string _email;

    public string Id
    {
        get { return _id; }
        set { _id = value; }
    }

    public string Firstname
    {
        get { return _firstname; }
        set { _firstname = value; }
    }

    public string Lastname
    {
        get { return _lastname; }
        set { _lastname = value; }
    }

    public string Email
    {
        get { return _email; }
        set { _email = value; }
    }
}

As you can see its way to long. Lets see how post .NET 2.0 does it.

public class Profile
{
    public string Id { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Email { get; set; }
}

Now thats what i’m talking about. Good work team. Thats how easy it should be to create a class!

Til’ Next Time, It’s Schotime Out!