Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all pattern indexes in string in C#

How can I find all indexes of a pattern in a string using c#?

For example I want to find all ## pattern indexes in a string like this 45##78$$#56$$JK01UU

like image 527
sanchop22 Avatar asked May 11 '12 06:05

sanchop22


Video Answer


2 Answers

 string pattern = "##";
 string sentence = "45##78$$#56$$J##K01UU";
 IList<int> indeces = new List<int>();
 foreach (Match match in Regex.Matches(sentence, pattern))
 {
      indeces.Add(match.Index);
 }

indeces will have 2, 14

like image 67
Prashanth Thurairatnam Avatar answered Oct 02 '22 16:10

Prashanth Thurairatnam


Edited the code to make it a cleaner function.

public IEnumerable<int> FindAllIndexes(string str, string pattern)
{
    int prevIndex = -pattern.Length; // so we start at index 0
    int index;
    while((index = str.IndexOf(pattern, prevIndex + pattern.Length)) != -1)
    {
        prevIndex = index;
        yield return index;
    }
}

string str = "45##78$$#56$$JK01UU";
string pattern = "##";

var indexes = FindAllIndexes(str, pattern);
like image 34
jb. Avatar answered Oct 02 '22 14:10

jb.