悠悠楠杉
网站页面
首先,我们需要定义正则表达式模式来匹配标题、关键词、描述和正文:
#
开头。,
分隔的多个词或短语。```csharp
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
string exampleText = @"
, 探索, 编程, 文本处理
此段为简短描述,涵盖主要内容。
详细介绍.NET正则表达式的应用,包括基本概念、高级功能等。";
(string title, string keywords, string description, string body) = ExtractSections(exampleText);
Console.WriteLine(GenerateMarkdown(title, keywords, description, body));
}
static (string title, string keywords, string description, string body) ExtractSections(string text)
{
// 匹配标题
var titleMatch = Regex.Match(text, @"^\#(.*?)(\n|\s+)");
if (titleMatch.Success) title = titleMatch.Groups[1].Value;
else title = "无标题";
// 移除标题后开始处到关键词的空白行或空格
var trimmedText = Regex.Replace(text, @"\n\s+|\s+", "\n", RegexOptions.Multiline);
var keywordsMatch = Regex.Match(trimmedText, @",\s*(.*?)\s*(\n|\s+)");
if (keywordsMatch.Success) keywords = keywordsMatch.Groups[1].Value;
else keywords = "无关键词";
// 匹配描述和正文
var descriptionMatch = Regex.Match(trimmedText, @"\n([\s\S]*?)\n", RegexOptions.Singleline);
if (descriptionMatch.Success) description = descriptionMatch.Groups[1].Value;
else description = "无描述";
body = trimmedText.Substring(descriptionMatch.Index + descriptionMatch.Length); // 剩余部分为正文
return (title, keywords, description, body);
}
static string GenerateMarkdown(string title, string keywords, string description, string body)
{
return $"## {title}\n\n*{keywords}*\n\n{description}\n\n---\n\n{body}";
}
}
```
方法将这些部分转换为Markdown格式的文本并输出。输出结果会以Markdown格式清晰地展示文章的标题、关键词、描述和正文。这对于生成或编辑文章大纲特别有用。