1

What would be the regular expression for finding img tags without a width or height attribute? I have tried regex <img(?!.*width).*?> for width and <img(?!.*height).*?> for height .

Will it works without conflict and what is the combination of both regex ?

4
  • 1
    Ermm just put | (logical or) between them? Like: <img(?!.*width).*?>|<img(?!.*height).*?>. Not to mention you shouldn't parse HTML with regex. Commented Nov 25, 2013 at 10:09
  • 1
    Obligatory link Commented Nov 25, 2013 at 10:09
  • Is any css parser available in java ? Commented Nov 25, 2013 at 10:13
  • yes, there are quite a good number of css parsers. You may want to check out this - stackoverflow.com/questions/1513587/… Commented Nov 25, 2013 at 23:18

1 Answer 1

1

Solution

Since you are using Java, here is a simple example for matching img tags without a width or height attribute. I used the Jsoup html parser:

Document doc = Jsoup.parse(myHtmlCode).get();
Elements imgsWithoutHeighOrWidth = doc.select("img:not(img[height], img[width])");

Demo

http://try.jsoup.org/~z1zP_fkmQPOi4Nbj87omMgbDbr0

Explanation

The big part here is the cssQuery passed to the select method.

I asked it to find:

img               => any img tags
   :not(          => not in 
      img[height] =>   any img tags with an `height` tag
      ,           =>   or
      img[width]  =>   any img tags with a `width` tag
   )
Sign up to request clarification or add additional context in comments.

2 Comments

Thank Alex for your response , Is there a way to retrieve <img> tag start line & column number and end line & column number ? Because i need to highlight <img> tag (without width/height) in my own html editor .
@user2998596 I don't jnow how to do that. However, you can use the .html() method of an Element for getting the position of this element inside myHtmlCode. Checl Jsoup javaodc for more help: jsoup.org/apidocs

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.