正则表达式:匹配字符+换行之前(换行换行)

细绳:


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)

返回:


\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

但是,这错过了我认为与 [\s\S] 有关的第一个 '\n\n'。我们有什么办法可以在第一个 '\n\n' 处结束搜索?


人到中年有点甜
浏览 60回答 1
1回答

慕的地10843

重复*器是贪心的,它尽可能多地匹配直到\n\n(这是字符串中的最后一次出现)。在它后面放一个问号以使其不贪婪,以便它尽可能少地匹配:直到它匹配的第一次出现\n\n:test = re.search('(Hello)([\s\S]*?)(\n\n)', testing).group(2)print(test)输出:HelloMy name is blah blah blahNice to meet youPS: Wait a second, I thought I know you.Regards
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python