简体   繁体   English

如何将搜索词解析为各种问题类型?

[英]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 员工ID
  • name (first or last) 名字(第一个或最后一个)
  • companyId companyId
  • status (workingFullTime, sickLeave, maternityLeave, etc) status(workingFullTime,sickLeave,maternityLeave等)

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) 蛮力的方法是简单地为每种类型的查询创建一个webform,并有一个菜单,用户可以选择要执行的查询类型(这是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. 例如,employeeId是一个精确格式的数字。 So I can do a regular expression to match that. 所以我可以做一个正则表达式来匹配它。 And the same is true for status, companyId, etc. 对于status,companyId等也是如此。

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. 所以我的问题是,如果这里有人可以提供一些建议,如何在C#中最好地编写一个方法,它将采用一个字符串并将其与许多不同的正则表达式进行匹配。

Cheers, Joakim 干杯,Joakim

The straight-forward way would be to have a sequence of if statements testing each regex in turn: 直接的方法是让一系列if语句依次测试每个正则表达式:

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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