示例字符串:<img width=100 src="files.jpg"> This is a test page <img width=100 src="files2.jpg">  world, html <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> 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",另外取到的字符串中还应该含有 "hello"和"test"两个关键词。
例如前面的字符串中需要取到"<img width=100 src="files2.jpg"> hello world, html test <img width=100 src="ffword.jpg"> from here, wodd. <span></span>"
而其他的均不能匹配。
如以下字符串除了开始有<img,中间还有一个<img,所以不能匹配。
<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> 不匹配以下的也不能匹配(因为不含有hello和test)。<img width=100 src="files2.jpg">  world, html <img width=100 src="ffword.jpg"> from here, wodd. <span></span>请教这个正则表示式该如何取?

解决方案 »

  1.   


    需求自相矛盾,你给的匹配结果中分明是有两个<img,怎么说是只有一个?难道是说中间必须包含且只能包含一个?
      

  2.   

    如果是结果中只有一个<img...>,且含有hello和test关键字的            Regex reg = new Regex(@"(?is)<img[^>]*>(\bhello\b(?<o>)|\btest\b(?<p>)|(?!<img).)*(?(o)|(?!))(?(p)|(?!))<span></span>");
                MatchCollection mc = reg.Matches(yourStr);
                foreach (Match m in mc)
                {
                    richTextBox2.Text += m.Value + "\n";
                }