C# Regexp选择带有空白的图像

C# Regexp选择带有空白的图像,c#,regex,C#,Regex,我尝试了几种组合,但最终还是插入了所有可能的符号 我有一个regexp,看起来像 <img[^>]*?src=["']([\w:\\\/\s\S]*[.a-zA-Z]{3,})[^>]*?> Sample <img alt="foo" src="c:\my-folder\contains.dot\and space\in myImagePath.png" title="bar" > 我最初使用的代码: <style>*{font-family:

我尝试了几种组合,但最终还是插入了所有可能的符号

我有一个regexp,看起来像

<img[^>]*?src=["']([\w:\\\/\s\S]*[.a-zA-Z]{3,})[^>]*?>
Sample <img alt="foo" src="c:\my-folder\contains.dot\and space\in myImagePath.png" title="bar" >
我最初使用的代码

<style>*{font-family: Arial, Helvetica, sans-serif;}</style><p><img src=\"C:\\Users\\JustMe\\Desktop\\de mo1.png\" width=\"1635\" height=\"989\" /></p>\n<p>&nbsp;</p>
using System.Text.RegularExpressions;

...

public List<string[]> FetchLinksFromSource(string htmlSource)
    {
        List<string[]> links = new List<string[]>();

        int i = 1;
        string regexImgSrc = @"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
        MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
        foreach (Match m in matchesImgSrc)
        {
            string[] matches = new string[3];
            string href = m.Groups[1].Value;
            matches[0] = href;
            matches[1] = new Uri(href).ToString();
            matches[2] = "imageID_" + i++.ToString();
            links.Add(matches);
        }
        return links;
    }
使用System.Text.regular表达式;
...
公共列表FetchLinksFromSource(字符串htmlSource)
{
列表链接=新列表();
int i=1;
字符串regexImgSrc=@“]+?)['”“][^>]*?>”;
MatchCollection matchesImgSrc=Regex.Matches(htmlSource、regexImgSrc、RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach(matchesImgSrc中的匹配m)
{
字符串[]匹配项=新字符串[3];
字符串href=m.Groups[1]。值;
匹配[0]=href;
匹配[1]=新Uri(href).ToString();
匹配[2]=“imageID_389;”+i++.ToString();
链接。添加(匹配项);
}
返回链接;
}
如果图像或路径有空格,此代码将崩溃

更改为:

<img[^>]*?src=["']([^"']*[.a-zA-Z]{3,})[^>]*?>
                   ^^^^^ 
]*?>
^^^^^ 

查看它

我更喜欢使用
\1
作为
src=
的结尾,在开头使用相同的“or”:

<img[^>]*?src=("|')(.*?)\1[^>]*?>
]*?>

FYI:
[\w:\\\/\s\s]*
=
[\s\s]*
==所有易于使用的东西[^\“]+:string input=”“;string pattern=“alt=\”(?'alt'[^\“]+)\“\\s+src=\”(?'src'[^\“]+)\“\\s+title=\”(?'title'[^\“]+)”;Match=Regex.Match(输入,模式);Console.WriteLine(“alt='{0}',src='{1}',title='{2}',match.Groups[“alt”].Value,match.Groups[“src”].Value,match.Groups[“title”].Value);Console.ReadLine();您确定要使用此页面中回答的正则表达式模式吗!?它们都不会与空格相撞@DWZA目前我使用原始代码示例中的一个。这会在空间上切割字符串。所有其他字符串似乎都找不到图像部分。我可以把它们包括错吗。。。。我不知道我是否必须用“看起来像”来逃避,但这不匹配。在演示链接或答案中的粘贴模式中出现“查看演示:”?在演示链接中我使用了
(.*)
,但在答案中的粘贴模式中,
(.*))
.Answer现在更新了。它仍然匹配整个img标记,而且不仅图像链接匹配和捕获是两件不同的事情。src在第二个捕获组中。@Dwzaah,我看到类型是javascript…我更改了它,它作为expactedcant在c中运行:/@Dwza
新Uri(href).ToString()
如果您的
href
中包含spacesok,这将无法工作,还不错……我可以稍后更改……但首先我需要正则表达式工作,以便它将imagepath与白色匹配spaces@Dwza您提供的代码不包括我的regexi know…因为它不起作用。至少当我在c#中使用它时不会。我必须将“替换为”吗 ?