C# 如何多次检查字符串的特定模式?

C# 如何多次检查字符串的特定模式?,c#,string,C#,String,我有一个字符串(一个网站的源代码)。我想多次检查字符串。我目前使用以下代码: string verified = "starting"; if (s.Contains(verified)) { int startIndex = s.IndexOf(verified); int endIndex = s.IndexOf("ending", startIndex); string verifiedVal = s.Substring(startIndex + verified.

我有一个字符串(一个网站的源代码)。我想多次检查字符串。我目前使用以下代码:

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);
}
代码确实有效,但它只对找到的第一个字符串有效。字符串中有1个以上的外观,如何才能找到它们并将其添加到列表中


谢谢。

您可以使用正则表达式来实现:

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

如果您不需要空字符串,可以将Regex中的
更改为
)+

您必须只查找发生的事件,或者您需要每个发生的事件的索引?@PareshGami我只想查找“开始”和“结束”之间的值。存在多个值。这是否适用于“startingXstartingYendingXending”之类的嵌套表达式?否。
s.IndexOf(…)
也会对嵌套字符串失败。可以创建一个正则表达式来处理嵌套表达式,但问题是在外部匹配的情况下,应该向
imgCodes
添加什么值。如果我要使用
数据条目id=“
来开始,使用
数据页码
来结束,我该怎么做?我试着替换
开始
结束
,但不起作用。很抱歉,我是新加入Regex的。我更改了开头和结尾的示例代码。谢谢,非常感谢。我看不到结尾模式和代码的使用,它们提取了开头和结尾之间的字符串。
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)
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();
    }
}