示例字符串:<img width=100 src="files.jpg"> This is a test page <img width=100 src="files2.jpg"> hello world, html test <img width=100 src="ffword.jpg"> from here, wodd. <span></span> This is a test page <img width=100 src="files2.jpg"> hello world, html test <img width=100 src="ffword.jpg"> from here, wodd. <span></span>
取所有以"<img"开始和以"<span></span>"结束之间的字符串,但取到的字符串中只能含有一个"<img"例如前面的字符串中需要取到"<img width=100 src="files2.jpg"> hello world, html test <img width=100 src="ffword.jpg"> from here, wodd. <span></span>"
而不是
<img width=100 src="files.jpg"> This is a test page <img width=100 src="files2.jpg"> hello world, html test <img width=100 src="ffword.jpg"> from here, wodd. <span></span>
请教这个正则表示式该如何取?

解决方案 »

  1.   

    string str = @"<img width=100 src=""files.jpg""> This is a test page <img width=100 src=""files2.jpg""> hello world, html test <img width=100 src=""ffword.jpg""> from here, wodd. <span></span> This is a test page <img width=100 src=""files2.jpg""> hello world, html test <img width=100 src=""ffword.jpg""> from here, wodd. <span></span>";
                MatchCollection mc = Regex.Matches(str, @"<img((?!img)[\s\S])+?<span></span>");
                foreach (Match m in mc)
                {
                    Console.WriteLine(m);
                }
      

  2.   

      string str="<img width=100 src=\"files.jpg\"> This is a test page <img width=100 src=\"files2.jpg\"> hello world, html test <img width=100 src=\"ffword.jpg\"> from here, wodd. <span></span>";
                Regex reg = new Regex(@"(?is)<img\swidth=100[^>]*>(.*?)<span></span>");
                MatchCollection mc = reg.Matches(str);
                foreach (Match m in mc)
                {
                    Console.Write(m.Groups[1].Value + "\n");
                }
     This is a test page <img width=100 src="files2.jpg"> hello world, html test <img width=100 src="ffword.jpg"> from here, wodd. 
      

  3.   

    string str="<img width=100 src=\"files.jpg\"> This is a test page <img width=100 src=\"files2.jpg\"> hello world, html test <img width=100 src=\"ffword.jpg\"> from here, wodd. <span></span>";
      Regex reg = new Regex(@"(?is)<img\swidth=100[^>]*>(.*?)<span></span>");
      MatchCollection mc = reg.Matches(str);
      foreach (Match m in mc)
      {
      Console.Write(m.Groups[1].Value + "\n");
      }
     This is a test page <img width=100 src="files2.jpg"> hello world, html test <img width=100 src="ffword.jpg"> from here, wodd.
    二楼的这个是正确的,我试的!
      

  4.   

     1 楼的也是对的,而且更通用一些。另外想问一下,如果匹配出的字符串中同时需要有"keyword1"和"keyword2",一楼的正则表达式<img((?!img)[\s\S])+?<span></span>该如何修改呢?
      

  5.   

    怎么分组呢?不能包含"<img",但同时需要包含keyword1和keyword2.