C# 验证img标签有没有包含width
时间: 2023-07-12 19:32:08 浏览: 53
可以使用C#的正则表达式来验证 img 标签是否包含 width 属性。以下是一个示例代码:
```csharp
string imgTag = "<img src=\"example.jpg\" width=\"100\" height=\"100\">";
string pattern = "<img[^>]+width\\s*=\\s*\"?(?<width>[^\"\\s>]+)\"?[^>]*>";
Match match = Regex.Match(imgTag, pattern, RegexOptions.IgnoreCase);
if (match.Success)
{
string width = match.Groups["width"].Value;
Console.WriteLine("img 标签包含 width 属性,值为:" + width);
}
else
{
Console.WriteLine("img 标签不包含 width 属性。");
}
```
解释:
- `imgTag` 是待验证的标签字符串。
- `pattern` 是正则表达式模式。它匹配 img 标签中的 width 属性,并使用命名捕获组 `(?<width>[^"\\s>]+)` 提取属性值。其中,`[^"\\s>]+` 表示匹配不包含双引号、空格和大于号的任意字符序列。
- `Regex.Match` 方法使用正则表达式模式在 `imgTag` 中查找匹配项。
- 如果找到匹配项,则从命名捕获组 `width` 中获取属性值,并输出到控制台。
- 如果未找到匹配项,则输出提示信息到控制台。