我无法让我的正则表达式工作(大惊喜)
我正在尝试用大量文本替换网址:
<img src="http://www.example.com/any/number/of/directories/picture.jpg" ...
<img src="http://www.example.com/any/number/of/directories/picture.gif" ...
使用:
<img src="/LocalDirectory/images/picture.jpg" ...
我想维护图片的名称,我不能有任何虚假的假设,因为原始文本将包含我想单独留下的其他网址。我只想修改图片,以便匹配jpg | jpeg | gif | png等或者
我在C#中这样做。
答案 0 :(得分:3)
因为我已经有了这个方便,所以应该抓住URL本身:
(?<=src=")[^"]+(?=")
在Regex Hero中验证,此正则表达式使用正向lookbehind和正向前导来获取src =“”内部的url。
我会看看我是否可以提出更具体的任务......
好的,这应该有效:
(?<=src=")[^"]+(/[^/]+(\.jpg|\.gif))(?=")
然后您可以使用替换值:
/LocalDirectory/images$1
或者这是完整的C#代码:
string strRegex = "(?<=src=\")[^\"]+(/[^/]+(\.jpg|\.gif))(?=\")";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = "<img src=\"http://www.example.com/any/number/of/directories/picture.jpg\" />" & vbCrLf & "<img src=\"http://www.example.com/any/number/of/directories/picture.gif\" />";
string strReplace = "/LocalDirectory/images$1";
return myRegex.Replace(strTargetString, strReplace);
答案 1 :(得分:1)
与正则表达式匹配的URL非常困难,如果不是不可能的话。除非您对文档中的URL包含一些额外的限制,否则您可以牺牲正则表达式的灵活性来换取实用性。
答案 2 :(得分:1)
strTargetString = "img tags to check";
string strRegex = "src=\"(.*)/(.*)\.(jpg|png|gif)\"";
RegexOptions myRegexOptions = RegexOptions.Multiline | RegexOptions.IgnorePatternWhitespace;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strReplace = "src="\/LocalDirectory\/images\/$2\.$3"";
return myRegex.Replace(strTargetString, strReplace);
误读了这个问题。这将替换jpg,png和gif的路径的第一部分并保留文件名。其他任何事情都被忽略了
答案 3 :(得分:1)
希望这会有所帮助:
var replace = "/localserver/some/directory/";
var strs = new List<string>
{
"<img src=\"http://www.example.com/any/number/of/directories/picture.jpg\"",
"<img src=\"http://www.example.com/any/number/of/directories/picture.gif\""
};
Regex r = new Regex("[^<img src=\"].*/");
foreach (var s in strs)
{
Console.WriteLine("Replaced: {0}",r.Replace(s,replace));
}
输出:
Replaced: <img src="/localserver/some/directory/picture.jpg"
Replaced: <img src="/localserver/some/directory/picture.gif"