1

我有一段文字:

我们美国人民,为了建立一个更完美的联盟,建立正义,确保国内安宁,提供共同防御,促进普遍福利,并确保我们自己和我们的后代获得自由的祝福,为美利坚合众国制定本宪法。

然后我有包含几个关键词的列表:

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

这是我想要的用法:

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

因此调用 GetOrderOfOccurence(preamble, keywords) 将按顺序返回以下内容:

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

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

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

4

2 回答 2

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"}
于 2012-12-06T04:14:12.953 回答
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

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

于 2012-12-06T04:42:23.277 回答