tags:

views:

136

answers:

3

I am writing an internal application where we let users to do a few different types of queries.

The application allows users to search a database by either of the following keys:

  • employeeId
  • name (first or last)
  • companyId
  • status (workingFullTime, sickLeave, maternityLeave, etc)

The brute force way is to simply make one webform for each type of query and have a menu where the user chooses which type of query to perform (this is ASP.NET)

But what I would like is to have a simple text box where the user enters the query and then the application should parse the query and automatically select the type of query to issue to the back end.

For example, the employeeId is a number of a precise format. So I can do a regular expression to match that. And the same is true for status, companyId, etc.

So my questions is if anyone here can give some advice on how to best code a method in C# that will take a string and match it against a number of different regular expressions.

Cheers, Joakim

+1  A: 

The straight-forward way would be to have a sequence of if statements testing each regex in turn:

if (Regex.Match(query, regex1)) {
    HandleFirstCase(query);
} else if(Regex.Match(query, regex2)) {
    HandleSecondCase(query);
} ... 
else {
    HandleFullTextSearch();
}

A more sophisticated way would be a data driven approach, where you store the regexes and actions in a table and loop over them:

public class RegexAction {
    public Regex Pattern { get; private set; }
    public Action<string> Handler { get; private set; }
    public RegexAction(Regex pattern, Action<string> handler) {
        this.Pattern = pattern;
        this.Handler = handler;
    }
}

public static RegexAction[] HandlerTable = new RegexAction[] {
    new RegexAction(regex1, HandleFirstCase),
    new RegexAction(regex2, HandleSecondCase),
    new RegexAction(regex3, HandleThirdCase),
    // ...
}

foreach(RegexAction action in HandlerTable) {
    if (action.Match(query)) {
        action.Handler(query);
        break;
    }
}

This helps separating the important data, patterns and actions, from the implementation of testing and calling.

David Schmitt
+1  A: 

Take a look at this question:
Efficiently querying one string against multiple regexes.

MizardX
+1  A: 

What I would do is just one OR query:

select * from employee where employeeId = search OR name like "%search%" OR status = "search"
serg