正则表达式替换<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);
//生成唯一的图片的名字
fileName = channelId.ToString() + "_ " + DateTime.Now.ToFileTime().ToString() + tempMatch;
//生成文件的路径
path = ConstantClass.CHANNEL_IMAGE_PATH + fileName;
//联网取图片
(new ConnectionDeal()).GetImage(matchValue, path);
}
catch
{
}
return fileName;
}
[解决办法]
private void simpleButton1_Click(object sender, EventArgs e)
{
WebRequest wreq = WebRequest.Create(new Uri( "http://www.google.cn/intl/zh-CN/ "));
WebResponse wresp = wreq.GetResponse();
StreamReader sr = new StreamReader(wresp.GetResponseStream(), Encoding.Default);
string htmlSource = sr.ReadToEnd();
memoEdit1.Text = Regex.Replace(htmlSource, @ "src= " "[^ " "]* " " ", new MatchEvaluator(GetNewImageTag),
RegexOptions.IgnoreCase
| RegexOptions.Multiline
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled);
}
private string GetNewImageTag(Match match)
{
//存储的方法,放到localhost/web下,记录下名字存入imgName
...
string imgName;
return match.Groups[1].Value + @ "src= " "/localhost/web/ " + imgName + @ ".jpg " " ";
}
}