【问题标题】:Find duplicate of words in string in a row连续查找字符串中单词的重复项
【发布时间】:2020-09-18 02:45:34
【问题描述】:
dictNum2 = {{"eins", 1}, {"zwei", 2}, {"drei", 3} ...};
foreach (KeyValuePair<string, int> dsa in dictNum2)
            {
                Regex regexTemp = new Regex(dsa.Key);
                MatchCollection matchTemp = regexTemp.Matches(stringInput);
            if ((stringInput.Contains(dsa.Key) && dsa.Value < 10))
                {
                    var indexList = Regex.Matches(stringInput, dsa.Key).Cast<Match>().Select(m => m.Index).ToList();
                    indexList.AddRange(indexList);
                    for(int i = 1; i < indexList.Count; i++)
                    {
                        if(indexList[i] == indexList[i-1] + dsa.Key.Length)
                        {
                            inaRow++;
                        }
                    }
                }
           }

这个想法是:需要找到一个字符串中彼此跟随的单词的数量,该字符串包含在字典中。我有一段代码适用于“zweizweizwei”之类的东西,但输入可能是这样的字符串:

“zweihundertzweidreiundzwanzig”或“zweiunddreieins

有办法解决吗?谢谢

【问题讨论】:

    标签: c# regex string


    【解决方案1】:

    对于正则表达式捕获的单词数,您可以使用Captures

    var dictNum2 = new Dictionary<string, int>() { { "eins", 1 }, { "zwei", 2 }, { "drei", 3 } };
    string stringInput = "zweihundertzweidreidreidreiundzwanzig";
    
    int inaRow = 0;
    var regex = new Regex("(" + string.Join("|", dictNum2.Keys) + ")+");
    foreach (Match m in regex.Matches(stringInput))
    {
        inaRow = Math.Max(inaRow, m.Groups[1].Captures.Count);
    }
    // inaRow is 4
    

    但如果你只是想知道是否有重复,那就更容易了

    var regex = new Regex("(" + string.Join("|", dictNum2.Keys) + "){2}");
    bool duplicate = regex.IsMatch(stringInput);
    

    【讨论】:

      【解决方案2】:

      在您的正则表达式

      中使用word boundaries
      Regex regexTemp = new Regex($"\b{dsa.Key}\b")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-29
        • 2021-06-30
        • 1970-01-01
        • 2017-10-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多