C# 句子中每个单词出现的索引

C# 句子中每个单词出现的索引,c#,regex,C#,Regex,我想找到“亲爱的”这个词出现在下面句子中的索引。这可以通过RegEx完成吗?如果是,怎么做 您好,亲爱的朋友,这是一个字符串,包含重复的字亲爱的;所以亲爱的,如果你能告诉我每个亲爱的在句子中的位置,那就太好了 我想这就是你需要的: string sentence = "Hello DEAR Friend, This is a string that contains repeititons of word dear; so my dear if you can keep coun

我想找到“亲爱的”这个词出现在下面句子中的索引。这可以通过RegEx完成吗?如果是,怎么做

您好,亲爱的朋友,这是一个字符串,包含重复的字亲爱的;所以亲爱的,如果你能告诉我每个亲爱的在句子中的位置,那就太好了


我想这就是你需要的:

        string sentence = "Hello DEAR Friend, This is a string that contains repeititons of word dear; so my dear if you can keep count of word dear used, it will be great";
        Regex r = new Regex(@"\bdear\b", RegexOptions.IgnoreCase);
        foreach (Match m in r.Matches(sentence))
        {
            MessageBox.Show(m.Index.ToString());
        }
试一试

这是字符开始位置的索引,如果这是您的意思。

尝试以下操作:

        Regex r = new Regex("dear",RegexOptions.IgnoreCase);
        string target = "Hello DEAR Friend, This is a string that contains repeititons of word dear; so my dear if you can tell me where each dear is located in the sentence, it will be great";
        MatchCollection allMatches = r.Matches(target);

allMatches
中的每个
Match
对象都有其匹配位置的索引。

我认为您不需要正则表达式,因为我非常喜欢它们,这个解决方案更简单:

int index = yourString.IndexOf("dear", StringComparison.OrdinalIgnoreCase);
while(index > -1)
{
    // Do whatever with the index here
    index = yourString.IndexOf("dear", index + 1, StringComparison.OrdinalIgnoreCase);
}

另一种简单的方法是使用列表理解,如下所示:

string1 = "This is the first airplane that flies around the world in far less time than the people thought"
print [i for i, j in enumerate(string1.split()) if j == 'the']

上面的代码查找所有出现的单词“The”。split()函数将句子拆分为单词。

@Navigate:它将如何为我提供每次事件的索引?这与他的示例中的第一次出现不匹配,是吗?如果“亲爱的”一词存在于其他单词(如“亲爱的”、“亲爱的”或“亲爱的”)中,您是否希望找到“亲爱的”一词?否则,需要修改当前的答案,以确保单词周围有非字母字符?
string1 = "This is the first airplane that flies around the world in far less time than the people thought"
print [i for i, j in enumerate(string1.split()) if j == 'the']