如何在Flutter中删除markdown语法并仅输出纯文本

abithluo  于 2023-01-02  发布在  Flutter
关注(0)|答案(1)|浏览(172)

有人知道如何在Flutter中删除字符串的Markdown语法吗?我查看了类似“markdown”和“flutter_markdown”的包,但没有找到任何函数。或者我应该创建一个自己的dart函数,并使用regex将其转换为纯文本?
编辑:我“创建”了一个方法来删除减价。问题是这是否足够,还是我错过了其他什么?

String removeMarkdown(String markdown) {
  // Replace bold text with plain text
  markdown = markdown.replaceAll(RegExp(r"\*\*(.+?)\*\*"), r"\1");

  // Replace italicized text with plain text
  markdown = markdown.replaceAll(RegExp(r"_(.+?)_"), r"\1");

  // Replace strikethrough text with plain text
  markdown = markdown.replaceAll(RegExp(r"~~(.+?)~~"), r"\1");

  // Remove inline code blocks
  markdown = markdown.replaceAll(RegExp(r"`(.+?)`"), "");

  // Remove code blocks
  markdown = markdown.replaceAll(RegExp(r"```[\s\S]*?```", multiLine: true), "");

  return markdown;
}

void main() {
  String markdown = "**bold** _italic_ ~~strikethrough~~ `inline code` ```code block```";
  print(removeMarkdown(markdown)); // Output: "bold italic strikethrough inline code code block"
}

编辑2:它看起来不完整,像标题丢失。

wa7juj8i

wa7juj8i1#

这应该行得通:

String removeMarkdown(String? markdown) {

  // Replace bold text with plain text
  markdown = markdown.replaceAll(RegExp(r'\*\*(.+?)\*\*'), '');
  markdown = markdown.replaceAll(RegExp('__(.+?)__'), '');

  // Replace italicized text with plain text
  markdown = markdown.replaceAll(RegExp('_(.+?)_'), '');
  markdown = markdown.replaceAll(RegExp(r'\*(.+?)\*'), '');

  // Replace strikethrough text with plain text
  markdown = markdown.replaceAll(RegExp('~~(.+?)~~'), '');

  // Replace inline code blocks with plain text
  markdown = markdown.replaceAll(RegExp('`(.+?)`'), '');

  // Replace code blocks with plain text
  markdown =
      markdown.replaceAll(RegExp(r'```[\s\S]*?```', multiLine: true), '');
  markdown =
      markdown.replaceAll(RegExp(r'```[\s\S]*?```', multiLine: true), '');

  // Remove links
  markdown = markdown.replaceAll(RegExp(r'\[(.+?)\]\((.+?)\)'), '');

  // Remove images
  markdown = markdown.replaceAll(RegExp(r'!\[(.+?)\]\((.+?)\)'), '');

  // Remove headings
  markdown =
      markdown.replaceAll(RegExp(r'^#+\s+(.+?)\s*$', multiLine: true), '');
  markdown = markdown.replaceAll(RegExp(r'^\s*=+\s*$', multiLine: true), '');
  markdown = markdown.replaceAll(RegExp(r'^\s*-+\s*$', multiLine: true), '');

  // Remove blockquotes
  markdown =
      markdown.replaceAll(RegExp(r'^\s*>\s+(.+?)\s*$', multiLine: true), '');

  // Remove lists
  markdown = markdown.replaceAll(
    RegExp(r'^\s*[\*\+-]\s+(.+?)\s*$', multiLine: true),
    '',
  );
  markdown = markdown.replaceAll(
    RegExp(r'^\s*\d+\.\s+(.+?)\s*$', multiLine: true),
    '',
  );

  // Remove horizontal lines
  markdown =
      markdown.replaceAll(RegExp(r'^\s*[-*_]{3,}\s*$', multiLine: true), '');

  return markdown;
}

相关问题