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 ”
有办法解决吗?谢谢
答案 0 :(得分:0)
答案 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);