这是一个您可以自己调整的开始:jsFiddle。
我做了两次替换,第一次添加<ul></ul>,然后添加<li></li>s。 (如果 JavaScript 支持后向断言,一步完成会更容易;如果没有它们,它仍然是可能的,但会很麻烦。)
val = val.replace(/((?:(?:^|[\n\r]+)[\t ]*-[\t ]*[^\n\r]*)+)/g, "\n<ul>\n$1\n</ul>");
val = val.replace(/[\n\r]+[\t ]*-[\t ]*([^\n\r]*)/g, "\n <li>$1</li>");
我在构建这个时做了一些假设,您可能需要撤消这些假设:
- 将一系列换行符视为一个换行符。
- 删除
- 前后的空格和制表符。
以下输入,
hello, world.
- two
- things
hi, again.
- three
-more
-things
创建以下输出:
hello, world.
<ul>
<li>two</li>
<li>things</li>
</ul>
hi, again.
<ul>
<li>three</li>
<li>more </li>
<li>things</li>
</ul>
解释
第一个正则表达式只是标识列表项的集合。
( Captured group ($1).
(?: Group (one list item). -------------------+
|
(?: Group (for alternation). ---------+ |
| |
^ Start-of-string | |
| |
| OR <-----+ |
|
[\n\r]+ one or more newlines. |
|
) |
|
[\t ]* (Ignore tabs and spaces.) |
- (Dash.) |
[\t ]* (Ignore tabs and spaces.) |
|
[^\n\r]* List item text (everything but newlines). |
|
) |
+ One or more list items. <-----------------+
)
在$1 中捕获的列表项集 包含在<ul></ul> 标签中:
"\n<ul>\n$1\n</ul>"
第二个正则表达式将每个列表项包装在<li></li> 标签中,并且与第一个非常相似,因此显示更改的内容可能更有用:
first regex : /((?:(?:^|[\n\r]+)[\t ]*-[\t ]* [^\n\r]* )+)/g
differences : xxxxxxxxx x ( )xxx
second regex : / [\n\r]+ [\t ]*-[\t ]*([^\n\r]*) /g
一句话,
我们不再关心列表项的 set,只关心 每个 列表项,因此我们可以删除用于量化的不可捕获组,(?:...)+,
1234563 p>
但是我们现在对捕获列表项文本感兴趣,因此我们添加了一个捕获组 (...)。