使用正则表达式查找没有alt属性的img标签

awr*_*ley 18 regex standards accessibility find visual-studio

我正在浏览一个大型网站(1600多页),使其通过优先级1 W3C WAI.因此,像图像标签之类的东西需要具有alt属性.

在没有alt属性的情况下查找img标签的正则表达式是什么?如果可能的话,有一个解释,所以我可以用来找到其他问题.

我在Visual Web Developer 2008的办公室里.编辑>>查找对话框可以使用正则表达式.

Gru*_*ffy 34

在Mr.Black和Roberts126的基础上回答:

/(<img(?!.*?alt=(['"]).*?\2)[^>]*)(>)/
Run Code Online (Sandbox Code Playgroud)

这将匹配代码中任何位置的img标记,该标记没有alt标记或alt标记,后面没有=""或=''(即无效的alt标记).

打破它:

(          : open capturing group
<img       : match the opening of an img tag
(?!        : open negative look-ahead
.*?        : lazy some or none to match any character
alt=(['"]) : match an 'alt' attribute followed by ' or " (and remember which for later)
.*?        : lazy some or none to match the value of the 'alt' attribute
\2)        : back-reference to the ' or " matched earlier
[^>]*      : match anything following the alt tag up to the closing '>' of the img tag
)          : close capturing group
(>)        : match the closing '>' of the img tag
Run Code Online (Sandbox Code Playgroud)

如果您的代码编辑器允许搜索和替换Regex,您可以将其与替换字符串结合使用:

$1 alt=""$3
Run Code Online (Sandbox Code Playgroud)

要查找任何无alt标记的img标记,并使用空的alt标记附加它们.当对HTML电子邮件等使用间隔符或其他布局图像时,这很有用.


squ*_*man 18

以下是我在自己的环境中尝试使用庞大的企业代码库并取得了一些成功(发现没有误报但肯定找到有效案例):

<img(?![^>]*\balt=)[^>]*?>
Run Code Online (Sandbox Code Playgroud)

这次搜索发生了什么:

  1. 找到标签的开头
  2. 寻找缺少零个或多个不是结束括号的字符,同时...
  3. 检查是否缺少以"alt"开头的单词("\ b"用于确保我们没有像类值那样得到中间名称匹配),后跟"=",然后 …
  4. 查找不是结束括号的零个或多个字符
  5. 找到结束括号

所以这将匹配:

<img src="foo.jpg" class="baltic" />
Run Code Online (Sandbox Code Playgroud)

但它不会匹配以下任何一个:

<img src="foo.jpg" class="baltic" alt="" />
<img src="foo.jpg" alt="I have a value.">
Run Code Online (Sandbox Code Playgroud)


Mr.*_*ack 8

这适用于Eclipse:

<img(?!.*alt).*?>

我也正在更新508节!


小智 7

这对我有用.

^<img(?!.*alt).*$
Run Code Online (Sandbox Code Playgroud)

这匹配任何<img以alt 开头的字符串,在alt属性之前不包含任意数量的字符.它甚至适用于src="<?php echo $imagename; ?>"属性类型.


Tho*_*mas 2

这确实很棘手,因为正则表达式主要是为了匹配现有的东西。通过环顾四周的技巧,你可以做一些事情,比如“找到 B 之前/之后没有的 A”等。但我认为对你来说最务实的解决方案不是这样。

我的建议有点依赖于您现有的代码不要做太疯狂的事情,您可能需要对其进行微调,但我认为如果您真的想使用正则表达式搜索来解决您的问题,这是一个很好的选择。

所以我建议是找到所有 img 标签,它们可以(但不需要)具有 img 元素的所有有效属性。这是否是您可以使用的方法由您决定。

提议:

/<img\s*((src|align|border|height|hspace|ismap|longdesc|usemap|vspace|width|class|dir|lang|style|title|id)="[^"]"\s*)*\s*\/?>/
Run Code Online (Sandbox Code Playgroud)

目前的限制是:

  1. 它期望您的属性值用双引号分隔,
  2. 它没有考虑可能的内联 on*Event 属性,
  3. 它找不到具有“非法”属性的 img 元素。