问题
I need a RegEx pattern for extracting all the properties of an image tag.
As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.
I was looking at this solution https://stackoverflow.com/questions/138313/how-to-extract-img-src-title-and-alt-from-html-using-php but it didn't quite get it all:
I come up something like:
(alt|title|src|height|width)\s*=\s*["'][\W\w]+?["']
Is there any possibilities I'll be missing or a more efficient simple pattern?
EDIT:
Sorry, I will be more specific, I'm doing this using .NET so it's on the server side.
I've already a list of img tags, now I just need to parse the properties.
回答1:
As we all know, there are lots of malformed HTML out there, so the pattern has to cover those possibilities.
It won't. Use a HTML parser if you have to parse "evil" (from an unknown source) HTML.
回答2:
If performance is not a big concern I'd go with an html parser (like BeautifulSoup in python) if you are doing this server-side or jquery or just plain javascript if you are doing it client-side. Granted it is overkill but it is a lot quicker, less likely to have bugs (since they've thought of the corner cases), and it will handle the potential malformedness.
回答3:
Your best bet is to use something like HTML Agility Pack instead of using regex. It's designed to handle a lot of cases and can save you more than a few headaches due to hammering out edge cases
回答4:
If you want all attribute values, might I suggest using the DOM? Something like element.attributes
will work well.
If you insist on a regex //\b\w+="[^"]+"//
should get everything.
回答5:
Before comitting yourself to regex, see what it can do: RegEx match open tags except XHTML self-contained tags
回答6:
/<img(\s+([a-z]{3,})=(["']([^"']*)["']|[\S]))+\s*/?>/i
A match_all on this, will return (format depends on your library, but key indexes are):
0 -> image tag
1 -> attribute
2 -> attribute name
3 -> attribute value (with enclosing quotes if exists)
4 -> attribute value (without enclosing quotes if it has them, otherwise empty, use 3)
来源:https://stackoverflow.com/questions/350250/regex-for-extracting-html-image-properties