正则表达式:匹配字符+换行之前(换行换行)
Regex: Match char + new line before (new line new line)
字符串:
testing = "\nHello\nMy name is blah blah blah\nNice to meet you\nPS: Wait a second, I thought I know you.\nRegards\n\nUnknown\n\nHang on a minute\nI'm not done talking\n\nRegards\nOh OK"
打印:
Hello
My name is blah blah blah
Nice to meet you
PS: Wait a second, I thought I know you.
Regards
Unknown
Hang on a minute
I'm not done talking
Regards
Oh OK
期望的结果:
My name is blah blah blah
Nice to meet you
PS: Wait a second, I thought I know you.
Regards
尝试的解决方案:
test = re.search('(Hello)([\s\S]*)(\n\n)', testing).group(2)
哪个returns:
\nMy name is blah blah blah\nNice to meet you\nPS: Wait a second, I thought I know you.\nRegards\n\nUnknown\n\nHang on a minute\nI'm not done talking
但是,这错过了第一个“\n\n”,我认为它与 [\s\S] 有关。有什么方法可以在第一个“\n\n”结束搜索?
谢谢!
*
重复器是 greedy,它尽可能匹配直到 \n\n
(这是字符串中的最后一次出现)。在它后面打一个问号,让它成为 non-greedy 所以它匹配的越少越好:直到它第一次出现匹配 \n\n
:
test = re.search('(Hello)([\s\S]*?)(\n\n)', testing).group(2)
print(test)
输出:
Hello
My name is blah blah blah
Nice to meet you
PS: Wait a second, I thought I know you.
Regards
字符串:
testing = "\nHello\nMy name is blah blah blah\nNice to meet you\nPS: Wait a second, I thought I know you.\nRegards\n\nUnknown\n\nHang on a minute\nI'm not done talking\n\nRegards\nOh OK"
打印:
Hello
My name is blah blah blah
Nice to meet you
PS: Wait a second, I thought I know you.
Regards
Unknown
Hang on a minute
I'm not done talking
Regards
Oh OK
期望的结果:
My name is blah blah blah
Nice to meet you
PS: Wait a second, I thought I know you.
Regards
尝试的解决方案:
test = re.search('(Hello)([\s\S]*)(\n\n)', testing).group(2)
哪个returns:
\nMy name is blah blah blah\nNice to meet you\nPS: Wait a second, I thought I know you.\nRegards\n\nUnknown\n\nHang on a minute\nI'm not done talking
但是,这错过了第一个“\n\n”,我认为它与 [\s\S] 有关。有什么方法可以在第一个“\n\n”结束搜索?
谢谢!
*
重复器是 greedy,它尽可能匹配直到 \n\n
(这是字符串中的最后一次出现)。在它后面打一个问号,让它成为 non-greedy 所以它匹配的越少越好:直到它第一次出现匹配 \n\n
:
test = re.search('(Hello)([\s\S]*?)(\n\n)', testing).group(2)
print(test)
输出:
Hello
My name is blah blah blah
Nice to meet you
PS: Wait a second, I thought I know you.
Regards