首页 > 解决方案 > 正则表达式 c# 与 https://regex101.com/ 给出的结果不同

问题描述

我有一些代码可以找到某些句子中每个单词中出现的一组字符(或任何字符)。例如:句子:“ex is ting pessim is t optim is t th is is ” 字符:“is” 出现次数:1(在 VS 中给出 2,在 regex101 中给出 3);2(在 VS 中给出 2,在 regex101 中给出 2);3(在 VS 中给出 2,在 regex101 中给出 1)。我不明白我在做什么。这是我的代码

    Regex regex;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.Append("([a-zA-Z]*[string]{numberOccur,}[^\\s][a-zA-Z]+\\s)");
    //Console.Write("Please input number of sentence: ");
    int NumerofSentence = Int32.Parse(Console.ReadLine());//Number of sentence want to check
    List<string> ListSentence = new List<string>();
    Console.Write("Input sentence: ");
    for (int index = 0; index < NumerofSentence; index++)
    {
        ListSentence.Add(Console.ReadLine());//Store in a collection object
    }
    //Console.Write("Input number of occurrences character in each word in sentence separated by non-word characters: ");
    int NumberOccur = Int32.Parse(Console.ReadLine());
    //Console.Write("Input character you want to find in all sentence: ");
    string stringFinded = Console.ReadLine();
    for (int index = 0; index < NumerofSentence; index++)
    {
        stringBuilder.Replace("string", stringFinded);
        stringBuilder.Replace("numberOccur", NumberOccur.ToString());
        regex = new Regex(stringBuilder.ToString());
        Match match = regex.Match(ListSentence[index]);
        if (match.Success)
        {
            Console.WriteLine(@"Sentences: {0}  
            Character: {1} 
            Number of occurrences in each sentences:   {2}",ListSentence[index],stringFinded,match.Groups.Count);
        }
        else
        {
            Console.WriteLine("Not found " );
        }
    }

标签: c#regex

解决方案


推荐阅读