Repository navigation
Expand file tree
/
Copy pathMarkdownPlainText.cs
More file actions
38 lines (33 loc) · 2.05 KB
/
Copy pathMarkdownPlainText.cs
File metadata and controls
38 lines (33 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System.Text.RegularExpressions;
namespace ShellDocs.Core;
// Prose-only text for search bodies: strips frontmatter, fences, tags/HTML and markdown syntax.
public static class MarkdownPlainText
{
private static readonly Regex Frontmatter = new(@"^---\s*\r?\n[\s\S]*?\r?\n---\s*\r?\n", RegexOptions.Compiled);
private static readonly Regex FencedBlock = new(@"^```[\s\S]*?^```", RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex HtmlTag = new(@"<[^>]+>", RegexOptions.Compiled);
private static readonly Regex Image = new(@"!\[([^\]]*)\]\([^\)]*\)", RegexOptions.Compiled);
private static readonly Regex Link = new(@"\[([^\]]+)\]\([^\)]*\)", RegexOptions.Compiled);
private static readonly Regex InlineCode = new(@"`([^`]+)`", RegexOptions.Compiled);
private static readonly Regex Emphasis = new(@"(\*\*|__|\*|_)(.+?)\1", RegexOptions.Compiled);
private static readonly Regex HeadingHash = new(@"^#{1,6}\s+", RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex ListMarker = new(@"^\s*[-*+]\s+|^\s*\d+\.\s+", RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex Blockquote = new(@"^>\s?", RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Regex WhitespaceRun = new(@"\s+", RegexOptions.Compiled);
public static string Extract(string markdown, int maxLength = 8000)
{
if (string.IsNullOrEmpty(markdown)) return "";
var text = Frontmatter.Replace(markdown, "");
text = FencedBlock.Replace(text, " ");
text = HtmlTag.Replace(text, " ");
text = Image.Replace(text, "$1");
text = Link.Replace(text, "$1");
text = InlineCode.Replace(text, "$1");
text = Emphasis.Replace(text, "$2");
text = HeadingHash.Replace(text, "");
text = ListMarker.Replace(text, "");
text = Blockquote.Replace(text, "");
text = WhitespaceRun.Replace(text, " ").Trim();
return text.Length > maxLength ? text[..maxLength] : text;
}
}