开发者

Index of each occurrence of word in sentence

I want to find index of each occurrence of word "dear" as it appear in following sentence. Can this be done via RegEx? If so how?

Hello DEAR Friend, This is a string that contai开发者_如何学Gons repeititons of word dear; so my dear if you can tell me where each dear is located in the sentence, it will be great


Try

foreach(Match m in Regex.Matches(mystring, "dear", RegexOptions.IgnoreCase))
{
   Debug.Writeline(m.Index);
}

This is index of the character where it starts, if that's what you mean.


I think this is what you need:

        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());
        }


try this:

        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);

Each Match object in allMatches will have the index of where it matched.


I don't think you need Regular Expressions, as much as I love them, this solution is easier:

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


Another easy way is using list comprehension like so:

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 above code finds all the occurrences of the word "the". The split() function splits the sentence into words.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜