问题描述
我正在尝试从以下示例文本中获取待办事项。
|| This is title ||
- item1
- item2
- item3
|| This is another title ||
我试过 /|| This is title ||\n\n(.*)+/
但它只抓取 item1
老实说我不知道如何为 `|| 编写正则表达式这是另一个标题 ||
我要抢 item1~3
解决方法
要将标题和项目分成两组,您可以使用 tempered greedy token(原为 from here),如
^\|\|\s+([^\n|]+)\s+\|\|((?:(?!^\|\|).)+)
这将捕获第一组中的标题和第二组中的所有项目。参见a demo on regex101.com(注意单行模式!)。
分解为:
^\|\|\s+ # start of the line,"||" and whitespace
([^\n|]+) # anything not "|" nor a newline - the title
\s+\|\| # whitespace,"||"
(
(?:(?!^\|\|).)+ # a neg. lookahead (?!...) that makes sure that no
) # line is captured that starts with "||"
之后,您可以简单地从第二组中使用 ^-(.+)
获取所有项目。
另一个选项可以重复匹配组中所有以 -
开头的行。
然后您可能会修剪结果,并在换行符处拆分。
^\|\|\s.*\s\|\|\n((?:\n- .*)+)
-
^
字符串开头 -
\|\|\s.*\s\|\|\n
匹配||
直到||
结束,然后是第一个换行符 -
(
捕获组 1-
(?:\n- .*)+
匹配换行符、-
和该行的其余部分
-
-
)
关闭群组
const regex = /^\|\|\s.*\s\|\|\n((?:\n- .*)+)/gm;
const str = `|| This is title ||
- item1
- item2
- item3
|| This is another title ||`;
Array.from(
str.matchAll(regex),m => console.log(m[1].trim().split("\n"))
);