tags:

views:

2508

answers:

3

I am using the following regex to get the src value of the first img tag in an HTML document.

string match = "src=(?:\"|\')?(?<imgSrc>[^>]*[^/].(?:jpg|png))(?:\"|\')?"

Now it captures total src attribute that I dont need. I just need the url inside the src attribute. How to do it?

+6  A: 

Parse your HTML with something else. HTML is not regular and thus regular expressions aren't at all suited to parsing it.

Use an HTML parser, or an XML parser if the HTML is strict. It's a lot easier to get the src attribute's value using XPath:

//img/@src

XML parsing is built into the System.Xml namespace. It's incredibly powerful. HTML parsing is a bit more difficult if the HTML isn't strict, but there are lots of libraries around that will do it for you.

Welbog
he's not looking to parse html, rather to simply extract a value from a single type of tag in html. Regexes excel at this sort of thing.
eqbridges
@eqbridges: The fact that the regex he's come up with is so complicated is an indication that it's the wrong way of going about the problem. Then there's the fact that it doesn't match all possible values for the src attributes (i.e. ones containing ' or "). Don't parse HTML/XML this way! Just don't do it!
Welbog
@Welbog -- if he only needs to get out a value of the img src, I respectfully disagree. Wielding an HTML parser on a task like that is overkill. If he needs to do anything particularly complex, then I'd be more likely to agree.
eqbridges
@eqbridges: You call it overkill, I call it simplicity. "//img/@src" is much simpler, readable and maintainable than "src=(?:\"|\')?(?<imgSrc>[^>]*[^/].(?:jpg|png))(?:\"|\')?", and above all it's actually correct.
Welbog
Does anyone have a good example of a tool that's not specific to c#?
Jeff Davis
@Jeff Davis: XPath, XQuery and XSL are all XML-related and not tied to any other programming languages.
Welbog
A: 

Your regex should (in english) match on any character after a quote, that is not a quote inside an tag on the src attribute.

In perl regex, it would be like this:

/src=[\"\']([^\"\']+)/

The URL will be in $1 after running this.

Of course, this assumes that the urls in your src attributes are quoted. You can modify the values in the [] brackets accordingly if they are not.

eqbridges
+4  A: 

see When not to use Regex in C# (or Java, C++ etc) and Looking for C# HTML parser

PS, how can I put a link to a StackOverflow question in a comment?

Ian Ringrose
Just post the url, you have 600 chars to comment with.
Ólafur Waage