简体   繁体   中英

How to parse a search term into the various question types?

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

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.

我要做的只是一个OR查询:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM