使用正则表达式配合 regex.matches 方法可以高效提取文本中特定标签之间的内容。通过构建包含捕获组的模式,如 <tag>(.*?)</tag>,并传入 regexoptions.singleline 标志以支持跨行匹配,即可获取所有目标片段。该方法适用于结构相对固定且无需处理复杂嵌套 html 的场景。

如何编写通用的标签提取函数
定义一个接受标签名和源文本的函数,利用正则表达式进行全局匹配。该函数返回一个字符串列表,包含所有匹配到的内容。若标签不存在或文本为空,则返回空列表。此方法避免了手动遍历字符串的繁琐,直接利用 .NET 内置的正则引擎完成提取。

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class TagExtractor
{
public static List<string> ExtractContent(string tagName, string source)
{
if (string.IsNullOrEmpty(source))
return new List<string>();
// 构建正则表达式:<tagName> 后跟任意字符(非贪婪),直到 </tagName>
// RegexOptions.Singleline 使 . 匹配换行符
string pattern = $"<{tagName}>(?<content>.*?)</{tagName}>";
MatchCollection matches = Regex.Matches(source, pattern, RegexOptions.Singleline);
var results = new List<string>();
foreach (Match match in matches)
{
results.Add(match.Groups["content"].Value);
}
return results;
}
public static void Main()
{
string text = @"<div>Hello</div>
<div>World</div>
<p>Test</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill2795" title="C#"><img
src="https://img.php.cn/upload/skill/000/000/081/178936933912641.jpg" alt="C#" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill2795" title="C#">C#</a>
<p>"避开 C# 常见错误——空陷阱、异步陷阱、LINQ 陷阱及资源泄漏。"</p>
</div>
<a href="/xiazai/skill2795" title="C#" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div>";
List<string> divs = ExtractContent("div", text);
foreach (var item in divs)
{
Console.WriteLine($"Extracted: {item}");
}
}
}运行上述代码,控制台将输出两行结果:Extracted: Hello 和 Extracted: World。这验证了函数能正确识别并提取指定标签内的文本,忽略其他标签。RegexOptions.Singleline 确保了即使标签内容包含换行符也能被完整捕获。
如何处理标签属性干扰匹配
当标签包含属性时,简单的 <tag></tag> 模式会失效。需修改正则表达式以允许标签名后跟随空格及任意属性,直到 > 符号。例如,将 <div> 改为 <code><div>]*>。这样可匹配 <code><div id="1"> 或 <code><div class="x"> 等变体,确保提取逻辑更健壮。<p><img src="https://img.php.cn/upload/article/001/431/639/179556711152292.png" alt="C#怎么从文本中提取某个标签之间的内容?"></p><pre class="brush:php;toolbar:false;">using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class RobustTagExtractor
{
public static List<string> ExtractWithAttributes(string tagName, string source)
{
if (string.IsNullOrEmpty(source))
return new List<string>();
// 修改模式:允许标签名后有非 > 字符(即属性)
string pattern = $"<{tagName}[^>]*>(?<content>.*?)</{tagName}>";
MatchCollection matches = Regex.Matches(source, pattern, RegexOptions.Singleline);
var results = new List<string>();
foreach (Match match in matches)
{
results.Add(match.Groups["content"].Value);
}
return results;
}
public static void Main()
{
string text = @"<div id="header">Title</div>
<div class="body">Content</div>";
List<string> items = ExtractWithAttributes("div", text);
foreach (var item in items)
{
Console.WriteLine($"Item: [{item}]");
}
}
}</pre><p>执行此程序,输出为:<code>Item: [Title] 和 Item: [Content]。这表明改进后的正则表达式成功忽略了标签中的属性部分,仅提取了内部文本。这种处理方式比硬编码标签名更具通用性,适用于大多数带有属性的标准 XML/HTML 标签。
当标签内容为空时会发生什么
如果源文本中包含自关闭标签(如 <br>)或成对标签内无内容(如 <span></span>),正则表达式 (.*?) 仍能匹配到空字符串。这意味着函数不会报错,而是将空值加入结果列表。开发者需注意,若业务逻辑要求忽略空内容,需在获取结果后增加过滤步骤,例如使用 Where(s => !string.IsNullOrEmpty(s)) 清理数据。

















