正则表达式:如何匹配文本实例,包括空格和换行符?
Regex: How to match instances of text, including spaces and new lines?
我想要一个正则表达式来匹配一个或多个后跟换行符的文本实例。在文本的最终匹配后跟一个换行符之后,我想要一个单独的换行符,然后不再。我将如何实现这一目标?
我在执行新行规则时遇到困难。
我的(错误)尝试包括:
[^\n]+\n\n
([^\n]+\n[^\n]+)*\n\n
我想要匹配的文本示例是:
"Hello text\nMore text\nLast one\n\n"
两者都不匹配:
"Hello text\nMore text\nLast one\n\n\n"
"Hello text\nMore text\nLast one\n"
请帮助我。谢谢
您要求匹配任意数量的文本行,最后仅跟 1 个额外的换行符,简单地说:^(.+\n)+\n(?!\n)
将执行您想要的操作。
此处示例:https://regex101.com/r/Hy3buP/1
解释:
^ - Assert position at start of string
(.+\n)+ - Match any positive number of lines of text ending in newline
\n - Match the next newline
(?!\n) - Do a negative lookahead to ascertain there are no more newlines.
我想要一个正则表达式来匹配一个或多个后跟换行符的文本实例。在文本的最终匹配后跟一个换行符之后,我想要一个单独的换行符,然后不再。我将如何实现这一目标?
我在执行新行规则时遇到困难。
我的(错误)尝试包括:
[^\n]+\n\n
([^\n]+\n[^\n]+)*\n\n
我想要匹配的文本示例是:
"Hello text\nMore text\nLast one\n\n"
两者都不匹配:
"Hello text\nMore text\nLast one\n\n\n"
"Hello text\nMore text\nLast one\n"
请帮助我。谢谢
您要求匹配任意数量的文本行,最后仅跟 1 个额外的换行符,简单地说:^(.+\n)+\n(?!\n)
将执行您想要的操作。
此处示例:https://regex101.com/r/Hy3buP/1
解释:
^ - Assert position at start of string
(.+\n)+ - Match any positive number of lines of text ending in newline
\n - Match the next newline
(?!\n) - Do a negative lookahead to ascertain there are no more newlines.