如何使用 Regex 识别在双换行符之后或文档开头开始的列表?
How do I identify lists that start after a double newline or at the beginning of a document with Regex?
假设我有以下文本块:
- one
some text
- should not start a list
- should start
- should continue
5. should also
6. more
我想在这里找到三个不同的列表,第一行,第6行和第7行,第9行和第10行。
因此,如果一个列表以两个换行符开头(它不能只在一个段落后的一行开始)或以文档开头,则该列表是有效的。
我试过:^(?<=\n{2})(?:(?:(?:\-)|(?:\d\.))( {1,})[^\n]*\n?)*$
它使用后视检查之前是否有两个换行符,它有效,但现在也导致它捕获 - one
列表。
"two newlines before or starts the document" 在正则表达式中怎么说?
编辑:澄清一下,它应该处于多行模式。语言是 PHP.
您可以使用正则表达式:
^(?:-|[0-9]).*|(?<=\n\n)(?:-|[0-9])(?:.|\n)*?(?=\n+[^-0-9]|$)
https://regex101.com/r/bW1zH1/3
我假设 'list' 以连字符或数字开头。
您没有指定您的编程语言,但是在 PCRE
中(PHP,等等),您可以想出以下正则表达式:
(?:^|(?:\R{2}))[-\d]
# match the start (^)
# or two newlines
# followed by a dash or a digit
参见a demo on regex101.com。
如果不支持\R
,尝试用[\n\r]
代替,这样就变成:
(?:^|(?:[\n\r]{2}))[-\d]
您可以使用这个正则表达式:
(?<=\n{2}|^)(?:(?:-|\d+\.) +.*\n?)+
正后视 (?<=\n{2}|^)
表示是否有 2 个前面的换行符或行首。
我还稍微重构了您的正则表达式以删除多余的捕获组。
假设我有以下文本块:
- one
some text
- should not start a list
- should start
- should continue
5. should also
6. more
我想在这里找到三个不同的列表,第一行,第6行和第7行,第9行和第10行。
因此,如果一个列表以两个换行符开头(它不能只在一个段落后的一行开始)或以文档开头,则该列表是有效的。
我试过:^(?<=\n{2})(?:(?:(?:\-)|(?:\d\.))( {1,})[^\n]*\n?)*$
它使用后视检查之前是否有两个换行符,它有效,但现在也导致它捕获 - one
列表。
"two newlines before or starts the document" 在正则表达式中怎么说?
编辑:澄清一下,它应该处于多行模式。语言是 PHP.
您可以使用正则表达式:
^(?:-|[0-9]).*|(?<=\n\n)(?:-|[0-9])(?:.|\n)*?(?=\n+[^-0-9]|$)
https://regex101.com/r/bW1zH1/3
我假设 'list' 以连字符或数字开头。
您没有指定您的编程语言,但是在 PCRE
中(PHP,等等),您可以想出以下正则表达式:
(?:^|(?:\R{2}))[-\d]
# match the start (^)
# or two newlines
# followed by a dash or a digit
参见a demo on regex101.com。
如果不支持\R
,尝试用[\n\r]
代替,这样就变成:
(?:^|(?:[\n\r]{2}))[-\d]
您可以使用这个正则表达式:
(?<=\n{2}|^)(?:(?:-|\d+\.) +.*\n?)+
正后视 (?<=\n{2}|^)
表示是否有 2 个前面的换行符或行首。
我还稍微重构了您的正则表达式以删除多余的捕获组。