我将一个文本文件读取到内存用(string类型),但是我要获取里面指定的多个相同字符该怎么获取,比如string s="sfd<%vfd%>fdsafd<%fdsfa%>fdfd<%fdsf%>fdfas";我现在是想获取所有<%.....%>这个标记里面的字符。如果用int start = s.indexof("<%");int end = s.indexof("%>");response.write(str.Substring(strat + 2, end - start - 2));方法,只能获取第一个标记的内容。怎么办能???

解决方案 »

  1.   

    很简单1。用特殊字符替换 <%和%>2。对字符串进行分割3。分割成的数组中,第一个元素和最后一个元素不要取就可以了
      

  2.   


                System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"<%[\w\W]*?%>");
                System.Text.RegularExpressions.MatchCollection mc = r.Matches(@"sfd<%vfd%>fdsafd<%fdsfa%>fdfd<%fdsf%>fdfas", 0);
                if (mc != null && mc.Count > 0)
                {
                    foreach (System.Text.RegularExpressions.Match m in mc)
                    {
                        MessageBox.Show(m.Value);
                    }
                }
      

  3.   


    string test = @"sfd<%vfd%>fdsafd<%fdsfa%>fdfd<%fdsf%>fdfas";
    MatchCollection mc = Regex.Matches(test, @"(?<=<%)((?!%>).)+");
    foreach (Match m in mc)
    {
        Console.WriteLine(m.Value);
    }
      

  4.   

    如果要支持多行string test = @"sfd<%vfd%>fdsafd<%fdsfa%>fdfd<%fdsf%>fdfas";
    MatchCollection mc = Regex.Matches(test, @"(?s)(?<=<%)((?!%>).)+");
    foreach (Match m in mc)
    {
        Console.WriteLine(m.Value);
    }
      

  5.   

    string str = "sfd<%111vfd%>fdsafd<%fdsfa2222%>fdfd<%f3333dsf%>fdfas";
                var result = System.Text.RegularExpressions.Regex.Matches(str, @"(?<=%)\w+(?=%)")
                    .OfType<System.Text.RegularExpressions.Match>()
                    .Select(x => x.Value);            foreach (var item in result) {
                    MessageBox.Show(item);
                }