2

This regular expression is only returning one match. (I'm looking to retrieve all image sources/locations (such as 'folder/image.png' contained in the src attribute in the img html tag).

Sample input string:

input = @"<p>here is an image</p><img attr=""ahwer"" src=""~/Images/logo.png"" st=""abc""/><p>some more text here</p>";
            s += @"<p>test</p><img src=""a.jpg"" /><img src=""folder/image.png"" />"

Pattern

pattern = @"<img.*src=""([^""]*)"".*/>";

The MatchCollection count is always 1 (oddly, only the last match, in this case 'folder/image.png'. Whenever I change the pattern to simply 'img', it finds all three image tags. So, it's likely my regex pattern is incorrect. I'm no regex guru and would appreciate any help.

2
  • Check to make sure you have the proper amount of double quotes. I'm not familiar with .NET's particular flavor of regex, but it looks like you have too many in both the target and pattern.
    – MikeD
    Jul 16, 2010 at 21:13
  • @MikeD: the quotes are okay. That's how you escape quotation marks in C#'s verbatim-string literals: by doubling them.
    – Alan Moore
    Jul 16, 2010 at 21:27

4 Answers 4

3

Do not parse HTML using regular expressions.

Instead, you should use the HTML Agility Pack, like this:

var doc = new HtmlDocument();
doc.Load(path);  
//Or 
doc.Parse(source);

var paths = doc.DocumentElement.Descendants("img")
                               .Select(img => img.Attributes["src"].Value);
1
  • Thanks for the link. However, I won't be doing major HTML manipulation so I'd rather not have to use a third party library.
    – Gabe
    Jul 16, 2010 at 21:18
2

Try pattern = @"<img.*?src=""([^""]*)"".*?/>"; - using .*? the matches should be non-greedy (i.e. not consume everything they can before matching vs. the next part).

1
  • This is it. Getting all three matches now. I thought of this just seconds before you posted it. Thanks!
    – Gabe
    Jul 16, 2010 at 21:17
0

The interior of your regex is too permissive, and it allows the match to swallow all of the image tags in one go.

But really, you shouldn't try to use a regex to parse HTML. Madness lies that way...

0

Try the pattern

pattern = @"(?<=.src="")[\w\/\.~]+";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.