使用正则表达式搜索列表中的文本?

时间:2012-12-06 03:44:39

标签: c# regex c#-4.0

我有一段文字:

  我们美国人民,为了形成更加完美   联盟,建立正义,保证国内宁静,提供   共同防御,促进一般福利,并确保   对自己和我们的后人的自由祝福,做到了   为美利坚合众国制定本宪法。

然后我将List包含几个关键词:

List<string> keywords = new List<string>()
{
  "Posterity",
  "Liberty",
  "Order",
  "Dinosaurs"
}

这是我想要的用法:

List<string> GetOrderOfOccurence(string text, List<string> keywords);

因此,调用GetOrderOfOccurence(序言,关键字)将按顺序返回以下内容:

{"Order"},
{"Liberty"},
{"Posterity"}

这可以通过关键字的for循环和前导码上的getIndexOf(关键字)轻松解决;然后将索引推入列表并返回该列表。如何使用正则表达式完成?假设我想在关键字列表中添加通配符?

System.Text.RegularExpressions.Regex.Matches()是否有使用模式列表的内容?

2 个答案:

答案 0 :(得分:3)

你必须使用正则表达式吗? Linq可能会这样做。

示例:

private List<string> GetOrderOfOccurence(string text, List<string> keywords)
{
    return keywords.Where(x => text.Contains(x)).OrderBy(x => text.IndexOf(x)).ToList();
}

返回

{"Order"},
{"Liberty"},
{"Posterity"}

答案 1 :(得分:0)

如果您希望使用正则表达式匹配字符串,则可以使用包含来自keywords的字符串集合的单个组作为模式(由管道 | 分隔)。然后,在text中搜索与此模式匹配的字符串,将其添加到新的List<string>,然后将其作为GetOrderOfOccurence(string text, List<string> keywords)

返回

示例

List<string> GetOrderOfOccurence(string text, List<string> keywords)
{
    List<string> target = new List<string>(); //Initialize a new List of string array of name target
    #region Creating the pattern
    string Pattern = "("; //Initialize a new string of name Pattern as "("
    foreach (string x in keywords) //Get x as a string for every string in keywords
    {
        Pattern +=  x + "|"; //Append the string + "|" to Pattern
    }
    Pattern = Pattern.Remove(Pattern.LastIndexOf('|')); //Remove the last pipeline character from Pattern
    Pattern += ")"; //Append ")" to the Pattern
    #endregion
    Regex _Regex = new Regex(Pattern); //Initialize a new class of Regex as _Regex
    foreach (Match item in _Regex.Matches(text)) //Get item as a Match for every Match in _Regex.Matches(text)
    {
        target.Add(item.Value); //Add the value of the item to the list we are going to return
    }
    return target; //Return the list
}
private void Form1_Load(object sender, EventArgs e)
{
    List<string> keywords = new List<string>(){"Posterity", "Liberty", "Order", "Dinosaurs"}; //Initialize a new List<string> of name keywords which contains 4 items
    foreach (string x in GetOrderOfOccurence("We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America.", keywords)) //Get x for every string in the List<string> returned by GetOrderOfOccurence(string text, List<string> keywords)
    {
        Debug.WriteLine(x); //Writes the string in the output Window
    }
}

<强>输出

Order
Liberty
Posterity

谢谢, 我希望你觉得这很有帮助:)