user5204184
user5204184

Reputation: 341

How can I check a string multiple times for certain pattern?

I have a string (a source code of a website). And I want to check for a string multiple times. I currently use this code:

string verified = "starting";
if (s.Contains(verified))
{
    int startIndex = s.IndexOf(verified);
    int endIndex = s.IndexOf("ending", startIndex);
    string verifiedVal = s.Substring(startIndex + verified.Length, (endIndex - (startIndex + verified.Length)));
    imgCodes.Add(verifiedVal);
}

The code does work, but it only works for the first string found. There are more than 1 appearances in the string, so how can I find them all and add them to the list?

Thanks.

Upvotes: 2

Views: 553

Answers (2)

Sebastian Schumann
Sebastian Schumann

Reputation: 3446

You can use Regex to do that:

var matches = Regex.Matches(s, @"starting(?<content>(?:(?!ending).)*)");
imgCodes.AddRange(matches.Cast<Match>().Select(x => x.Groups["content"].Value));

After that imgCodes will contain ALL substrings between starting and ending.

Sample:

var s = "afjaöklfdata-entry-id=\"aaa\" data-page-numberuiwotdata-entry-id=\"bbb\" data-page-numberweriouw";
var matches = Regex.Matches(s, @"data-entry-id=""(?<content>(?:(?!"" data-page-number).)+)");
var imgCodes = matches.Cast<Match>().Select(x => x.Groups["content"].Value).ToList();
// imgCode = ["aaa", "bbb"] (as List<string> of course)

If you don't need empty strings you can change .)* in Regex to .)+.

Upvotes: 2

Buda Gavril
Buda Gavril

Reputation: 21657

class Program
{
    static void Main(string[] args)
    {
        string s = "abc123djhfh123hfghh123jkj12";
        string v = "123";
        int index = 0;
        while (s.IndexOf(v, index) >= 0)
        {
            int startIndex = s.IndexOf(v, index);
            Console.WriteLine(startIndex);
            //do something with startIndex
            index = startIndex + v.Length ;
        }
        Console.ReadLine();
    }
}

Upvotes: 3

Related Questions