日期:2014-05-18  浏览次数:20797 次

初学正则,问个问题.
C# code
            string str = @" <img src=http://images.gg-art.com/auction/images1/13/13325.jpg >
<img src=http://images.gg-art.com/auction/images1/13/13326.jpg >
<img src=http://images.gg-art.com/auction/images1/13/13327.jpg >";
            Regex r = new Regex(@"<img[\s]*src[\s]*=(?<src>http://[\w\W]*.jpg)[\s]*>$", RegexOptions.Multiline);
            string oStr = "";
            if (r.IsMatch(str))
            {
                oStr += r.Match(str).Groups["src"].Value.ToString()+",";
            }
            Response.Write(oStr);

我是想把三个img的scr都输出来.如果只出现了一次就是正确的.

------解决方案--------------------
其实楼主的html代码不是格式良好的,src的属性值最好加上引号。如果属性有引号,下面的正则就出不起作用了
C# code

string str = @" <img src=http://images.gg-art.com/auction/images1/13/13325.jpg > <img src=http://images.gg-art.com/auction/images1/13/13326.jpg > <img src=http://images.gg-art.com/auction/images1/13/13327.jpg >";
string pattern = @"<img\ssrc=([^\s]*).*?>";
//Regex r = new Regex(@"<img[\s]*src[\s]*=(?<src>http://[\w\W]*.jpg)[\s]*>$", RegexOptions.Multiline); 
Regex r = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
//string oStr = ""; 
bool isMatch = r.IsMatch(str);

if (isMatch)
{
    MatchCollection mc = r.Matches(str);
    foreach (Match m in mc)
    {
        Response.Write(m.Groups[1].Value + "<br />");
    }
}

------解决方案--------------------
$这个表示最末的位置,而最末的位置只有一个哈...
没有看到循环哈-_-!!!!!!

参考如下代码:
C# code
string str = 
    @"<img src=http://images.gg-art.com/auction/images1/13/13325.jpg >
    <img src=http://images.gg-art.com/auction/images1/13/13326.jpg >
    <img src=http://images.gg-art.com/auction/images1/13/13327.jpg >";
Regex r = new Regex(@"<img\s+src\s*=\s*(?<src>[^\>]*?)\s*>");
string oStr = "";
foreach(Match vMatch in r.Matches(str))
{
    oStr += vMatch.Result("${src}") + ",";
}