C#用正则表达式 获取标签的属性或值
时间: 2023-07-27 11:07:35 浏览: 250
你可以使用正则表达式来匹配标签的属性或值,以下是一个 C# 示例代码:
```csharp
using System;
using System.Text.RegularExpressions;
class Program {
static void Main() {
string input = "<div class=\"my-class\" data-value=\"123\">Hello World!</div>";
string pattern = "(?<attr>\\w+)\\s*=\\s*(\"(?<value>[^\\\"]*)\"|'(?<value>[^']*)')";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches) {
Console.WriteLine("Attribute: {0}, Value: {1}", match.Groups["attr"].Value, match.Groups["value"].Value);
}
}
}
```
在上述示例中,我们使用正则表达式 `"(?<attr>\\w+)\\s*=\\s*(\"(?<value>[^\\\"]*)\"|'(?<value>[^']*)')"` 来匹配标签的属性或值。该正则表达式的含义是:首先匹配一个属性名(由字母、数字、下划线组成),然后匹配等号和属性值,其中属性值可以用单引号或双引号括起来。通过使用命名捕获组 `(?<attr>\\w+)` 和 `(?<value>[^\\\"]*)`,我们可以轻松地获取属性名和属性值。
阅读全文
相关推荐















