REGEX entry to match the src, height and width attributes of the img tag

I am trying to write a regex to match the src, width and height attributes on an image tag. Width and height are optional.

I came up with the following:

(?:<img.*)(?<=src=")(?<src>([\w\s://?=&.]*)?)?(?:.*)(?<height>(?<=height=")\d*)?(?:.*)(?<width>(?<=width=")(\d*)?)?

      

expresso shows that this only matches the src bit for the following html chunk

<img src="myimage.jpg" height="20" />
<img src="anotherImage.gif" width="30"/>

      

I hope I am really close and someone here can point out what I am doing wrong, I have a feeling that my optional bit between bit characters (?:. *), I tried to make it not greedy without success. So, any pointers?

+1


a source to share


4 answers


It is always a mistake to use regular expressions to pull values ​​from HTML. HTML syntax is much more complex than it might appear, and it is very easy for a page to rip out even a very complex regexp.

Use HTML Parser instead.



This question has been asked before and will be asked again. Regular expressions seem like a good choice for this problem, but they are not.

+9


a source


Regexes are fundamentally bad at parsing HTML (see Can you give some examples of why it is difficult to parse XML and HTML with regex? For what). You need an HTML parser. See Can you give an example of parsing HTML with your favorite parser? for examples using various parsers.



+3


a source


In most dialects, the regex .*

is greedy and will be oversaturated; use .*?

"as little as possible" to match.

+1


a source


I haven't had a chance to test it, but maybe this will work for you (note that I didn't use named matches):

<img(?:(\s*(src|height|width)\s*=\s*"([^"]+)"\s*)+|[^>]+?)*>

      

+1


a source







All Articles