连续查找字符串中单词的重复项

时间:2020-09-18 02:45:34

标签: c# regex string

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”之类的代码,但是在输入时可能是这样的字符串:

“ zweihundert zweidrei undzwanzig”或“ zweiund dreieins

有办法解决吗?谢谢

2 个答案:

答案 0 :(得分:0)

regex

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

答案 1 :(得分:0)

对于正则表达式捕获的单词数,您可以使用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);