string a = "<a>";
string b = "</a>";
string s = "<a>123</a><a>1123</a><a>123</a><a>132</a>";我希望得到s中,所有以a字符串开头,以b字符串结尾的字符串,也就是:
123
1123
123
132求一个比较灵活的解决办法,我需要根据不同的规则抓取网页中不同位置的字符串,谢谢了!

解决方案 »

  1.   

    贴段代码,希望对你有点作用:
    using System;
    using System.Text.RegularExpressions;
    public class StripHTMLTest{
      public static void Main(){
        string s=StripHTML("<HTML><HEAD><TITLE>中国石龙信息平台</TITLE></HEAD><BODY>faddfs龙信息平台</BODY></HTML>");
        Console.WriteLine(s);
      }  public static string StripHTML(string strHtml){
        string [] aryReg ={
              @"<script[^>]*?>.*?</script>",          @"<(\/\s*)?!?((\w+:)?\w+)(\w+(\s*=?\s*(([""'])(\\[""'tbnr]|[^\7])*?\7|\w+)|.{0})|\s)*?(\/\s*)?>",
              @"([\r\n])[\s]+",
              @"&(quot|#34);",
              @"&(amp|#38);",
              @"&(lt|#60);",
              @"&(gt|#62);", 
              @"&(nbsp|#160);", 
              @"&(iexcl|#161);",
              @"&(cent|#162);",
              @"&(pound|#163);",
              @"&(copy|#169);",
              @"&#(\d+);",
              @"-->",
              @"<!--.*\n"
             };    string [] aryRep = {
               "",
               "",
               "",
               "\"",
               "&",
               "<",
               ">",
               " ",
               "\xa1",//chr(161),
               "\xa2",//chr(162),
               "\xa3",//chr(163),
               "\xa9",//chr(169),
               "",
               "\r\n",
               ""
              };    string newReg =aryReg[0];
        string strOutput=strHtml;
        for(int i = 0;i<aryReg.Length;i++){
          Regex regex = new Regex(aryReg[i],RegexOptions.IgnoreCase);
          strOutput = regex.Replace(strOutput,aryRep[i]);
        }
        strOutput.Replace("<","");
        strOutput.Replace(">","");
        strOutput.Replace("\r\n","");
        return strOutput;
      }
    }
      

  2.   

    string s = @"<a>123</a>
    <a>1123</a>
    <a>123</a>
    <a>132</a>";System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex(@"^(<([^>]+)>)?(.*?)(<([^>]+)>)?\s*$");
    string[] ss = s.Split('\n');
    foreach (string s2 in ss)
    {
    System.Text.RegularExpressions.Match m = re.Match(s2);
    if (m.Success)
    Response.Write(m.Groups[3].Value+"<br>");
    }
      

  3.   

    字符串a和b不一定只是“<a>”这样的HTML标签形式,也有可能是汉字或者其他字符串
      

  4.   

    上面写法并没有限制必须a,还是b,只是通过<,>来操作的,所以即使有汉字也一样可以,不信你可以试试