views:

32

answers:

3

I am trying to capture img tag in HTML using Regex...

So these must be captured:

<img/>
< img id = "f" />

I have used:

"<\s*img(\s.*?)?/>"

But this goes wrong:

< img id = "/>" />

Any idea how to probably capture img tag??

Thanks

+2  A: 

On a serious note: Use an xml parser instead.

"<\simg\sid\s=\s\"(.*?)\"\s/>"

Also, you should look into using a regex testing suite like regex buddy.

This might be a good read as well: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags

Femaref
Thanks, please note the question was edited..
Betamoo
answer was edited as well.
Femaref
A: 
"<\s*img\s(?:.+?\s*=\s*(\"|')?.*?\1\s*)?/>"

I think this should take the quotes into account. Didn't test it though.

Core Xii
A: 

You can use this regex

<\s*?img[\s\S]*?/>

Shekhar