C#用正则表达式 获取标签的属性或值
时间: 2023-07-27 14:07:35 浏览: 57
可以使用正则表达式和 C# 中的 Match 和 Regex 类来获取 HTML 标签的属性或值。下面是一个示例代码:
```csharp
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
string html = "<div class=\"container\">Hello World</div>";
// 匹配 div 标签的 class 属性
string pattern = "<div.*?class=\"(.*?)\".*?>";
Match match = Regex.Match(html, pattern);
if (match.Success)
{
string value = match.Groups[1].Value;
Console.WriteLine(value); // 输出 "container"
}
// 匹配 div 标签的内容
pattern = "<div.*?>(.*?)</div>";
match = Regex.Match(html, pattern);
if (match.Success)
{
string value = match.Groups[1].Value;
Console.WriteLine(value); // 输出 "Hello World"
}
}
}
```
上面的代码示例演示了如何匹配 div 标签的 class 属性和内容。你可以根据需要修改正则表达式来匹配不同的标签和属性。