在字符串

时间:2017-06-02 01:05:34

标签: c# .net regex string linq

我尝试在所有这些情况下找到位于特定词组"is better"之前的左词,除了输入3

    string input = "I think that green bike is better than the red bike"; // input 1
    string input = "I think that green bike is better";                   // input 2
    string input = "is better than the red one";                          // input 3
    string input = "bike is better";                                      // input 4

我尝试了三种方法,但是这些方法中没有一种方法不能给我想要的结果,即只找到左边的单词,在这种情况下,在搜索短语{{"bike"之前它是单词"is better" 1}}在除输入3 之外的所有三个输入案例中都没有搜索短语本身:

1)

    var matches = Regex.Matches(input, @"(?:\S+\s)?\S*is better\S*(?:\s\S+)?", RegexOptions.IgnoreCase);
    var list = matches.Cast<Match>().Select(match => match.Value).ToList();

    foreach (string x in list)
    {
        Console.WriteLine("1) " + x);
    }

2)

     var regex = new Regex(@"(?:is better\s)(?<word>\b\S+\b)");
     var matchCollection = regex.Matches(input);

     foreach (Match match in matchCollection)
     {
        Console.WriteLine("2) " + match.Groups["word"].Value);
     }

第3)

string pattern = @"(?<before>\w+) is better (?<after>\w+)";           
MatchCollection matche = Regex.Matches(input, pattern);

for (int i = 0; i < matche.Count; i++)
{
    Console.WriteLine("3) before: " + matche[i].Groups["before"].ToString());
    Console.WriteLine("3) after: " + matche[i].Groups["after"].ToString());
}

输入1: "I think that green bike is better than the red bike"结果为:

1) bike is better than
2) than
3) before: bike
3) after: than

因此1)的结果是短语"is better"的左右两个词。 2)的结果是"then"之后的"is better"个字词。 3)的结果再次是前后两个词,正是我可以使用的,但是这个解决方案的问题显示在第二个结果中。

输入2: "I think that green bike is better"结果为:

1) bike is better

1)的结果是一个单词"bike",它位于短语"is better"之前,但带有搜索短语"is better"2)的结果没有任何意义,因为它在"is better"之后查找单词,因此它是正确的。如果3)之前的单词"bike"存在"is better""is better"的结果也没有结果,如果"is better than the red one"之后的单词不存在且它是字符串中的最后一个单词。< / p>

输入3: 1) is better than 2) than 结果为:

1)

"is better"的结果是"is better"之后存在的正确单词,因为之前的单词不存在,并且包含搜索短语1)。结果"then""is better"之后的单词"bike is better"

输入4: 1) bike is better

的结果
transform

2 个答案:

答案 0 :(得分:1)

试试这个:

\w+(?=\sis better)

除第3个输入外,它将匹配bike

答案 1 :(得分:0)

原始方式(\w+) is better第1组:会给你。