-1

I am trying to write a regex that looks for an img tag where there is no alt attribute.

Here is the regex.

<img\s+src.+^(?!alt).+$

Here are some samples

<img src="smiley.gif" alt="Smiley face" height="42" width="42">
<img src="smiley2.gif" height="42" width="42">
<img src="smiley3.gif" alt="Smiley face Three" height="42" width="42">

Here is a link to regex101 https://regex101.com/r/Z5vkQb/3/

Aaron
  • 4,380
  • 19
  • 85
  • 141

3 Answers3

2

Don't.

You haven't specified which language you're using, but chances are good you have a DOM parser available.

For example, in JavaScript, you can just do this:

var imgs_with_no_alt = document.querySelectorAll("img:not([alt])");

In PHP you would need something like this:

$dom = new DOMDocument();
$dom->loadHTML("your HTML here");
$images = $dom->getElementsByTagName("img");
foreach($images as $image) {
    if( $image->getAttribute("alt")) continue;
    // do something to $image here, which doesn't have an [alt] attribute
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

If within the same line, you can use this,

<img(?!.*\s+alt\s*=).+$

Demo

Pushpesh Kumar Rajwanshi
  • 18,127
  • 2
  • 19
  • 36
0

You can use this expression:

<img[^>]*alt=[^>]*>
Wilmer
  • 138
  • 1
  • 8