日期:2014-05-19  浏览次数:20886 次

正则表达式替换<img>中src问题
说明如下:
有如下字符串:
<img   alt= "一键进入教你快速访问Vista网络连接 "   alt=network-adaptors.jpg   src= "http://www.sinaimg.cn/IT/cr/2007/0704/3441139462.jpg "   style= "border:0px   solid   #000; "   _extended= "true ">

网页中许多这样的标记,现在的想法是要把其中的src地址改为本地地址,每个文件名应该是不同的,比如“/localhost/web/1.jpg”“/localhost/web/2.jpg”,该怎么弄啊?敬请各位大侠帮忙

------解决方案--------------------
src=(\\S*)\\.jpe?g
------解决方案--------------------
这样看看,是不是你要的效果

string result = Regex.Replace(yourStr, @ "( <img[^> ]*src=([ ' " "]?))[^ ' " "\s> ]*(\2[^> ]*> ) ", new MatchEvaluator(regReplace), RegexOptions.IgnoreCase);


int i = 0; //这个是全局变量
private string regReplace(Match m)
{
i++;
return m.Groups[1].Value + "/localhost/web/ " + i + ".jpg " + m.Groups[3].Value;
}
------解决方案--------------------
//处理内嵌图片
if (FormData.settingInfo.ChannelSetting.GetEnbededImage)
{
foreach (ItemInfo item in FormData.reNewInfo.ListItem)
{
//匹配出Description中的Image标签
try
{
//用于替换每个新闻项描述中的img标签
item.Description = Regex.Replace(item.Description,
@ " <img\s*src\s*=\s*[ " " ']?.+\s*.(gif|jpg|bmp|tif|png)\s*.+(\/> | <\/img> ) ",
new MatchEvaluator(GetNewImageTag),
RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
catch
{ }
}
}

/// <summary>
/// 返回替换后的image标签
/// </summary>
/// <param name= "match "> </param>
/// <returns> </returns>
private string GetNewImageTag(Match match)
{
string matchValue = match.Value;

try
{
//从image 标签中匹配出URL
matchValue = Regex.Replace(matchValue,
@ "[a-zA-z]+://[^\s]* ",
new MatchEvaluator(GetNewImageUrl),
RegexOptions.Compiled | RegexOptions.IgnoreCase);
}
catch
{

}

return matchValue;
}

/// <summary>
/// 联网取图片,并将新生成的图片名返回
/// </summary>
/// <param name= "match "> </param>
/// <returns> </returns>
private string GetNewImageUrl(Match match)
{
string matchValue = match.Value;
string path = string.Empty;
string fileName = string.Empty;

try
{
//从url中匹配出图片名字的后缀
Regex imageSuffixRegex = new Regex(@ "(\.bmp|\.jpg|\.gif|\.png) ", RegexOptions.Compiled);
Match tempMatch = imageSuffixRegex.Match(matchValue);

//生成