4

挑战:用正则表达式将整个 MarkDown 文件按照标题#拆分成子字符串

 2 years ago
source link: https://www.v2ex.com/t/790454
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

V2EX  ›  程序员

挑战:用正则表达式将整个 MarkDown 文件按照标题#拆分成子字符串

  AndyAO · 1 天前 · 400 次点击

也就是按照标题进行拆分,将每个标题 1,及其下辖内容,变成独立的字符串。

由于是挑战的性质,所以要求只调用正则表达式引擎 1 次就完成任务。

怎么才算赢呢?只要指出优越性就行,也许是性能,也许是可读性。

如果你想挑战的话可以试试看。

至于我的答案嘛,就放在最后了。

如果放 Match 对象,那么又要重复原文内容,这里放个图吧。

戳此查看

# 0

Content 0

## 0.0

Content 0.0

### 0.0.0

Content 0.0.0

#### 0.0.0.0

Content 0.0.0.0

### 0.0.1

Content 0.0.1

### 0.0.2

Content 0.0.2

## 0.1

Content 0.1

## 0.2

### 0.2.0

Content 0.2.0

### 0.2.1

Content 0.2.1

## 0.3

# 2

Content 2

# 3

Content 3

# 4

Content 4

我的答案是这样的,用捕获组是为了提取,也是为了加个分隔和注释,方便阅读。

C#的正则引擎对各种高级特性支持都比较好,我平常又比较常用,所以用的是这个。

断言在某些引擎上运行可能会失败,不要高估了正则表达式在不同引擎上的兼容性。

^(?<TitleSymbol>#)( )(?<Title>.+)(\n)(?<Content>[\s\S]+?)((?=(\n# ))|(?![\s\S]))


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK