arkTS 如何解析MD格式?

1. 尝试1

interface Interface_1 {
  heading: RegExp;
  listItem: RegExp;
  paragraph: RegExp;
}

const markdownRules: Interface_1 = {
  heading: /^#\s+(.*)$/,
  listItem: /^\s*-\s+(.*)$/,
  paragraph: /^([^\n]+)$/,
}

// 解析 Markdown 文本
function parseMarkdown(markdownText: string) {
  const lines: string[] = markdownText.split('\n');
  const jsonData: string[] = [];

  for (const line of lines) {
    if (markdownRules.heading.test(line)) {
      const res: RegExpMatchArray | null = line.match(markdownRules.heading)
      if (res) {
        const heading: string = res[1];
        jsonData.push(heading);
      }

    } else if (markdownRules.listItem.test(line)) {
      const res: RegExpMatchArray | null = line.match(markdownRules.listItem)
      if (res){
        const listItem:string= res[1];
        jsonData.push(listItem);
      }


    } else if (markdownRules.paragraph.test(line)) {
      const res: RegExpMatchArray | null = line.match(markdownRules.paragraph)
      if (res){
        const paragraph:string= res[1];
        jsonData.push(paragraph);
      }

    }
  }

  return jsonData;
}

interface LiteralInterface_1 {
  heading?: string;
  title?: string
}

let array: LiteralInterface_1[] = [];

// 添加对象
array.push({ heading: 'abc' });
array.push({ title: 'jjj' });

console.log('',JSON.stringify(array));
// 示例用法
const markdownText = `
# 标题
这是一段 Markdown 文本。

- 列表项 1
- 列表项 2
`;

const jsonData = parseMarkdown(markdownText);
console.log(JSON.stringify(jsonData, null, 2));

 

posted @ 2024-06-23 00:50  o蹲蹲o  阅读(2)  评论(0编辑  收藏  举报