细绳: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"打印:HelloMy name is blah blah blahNice to meet youPS: Wait a second, I thought I know you.RegardsUnknownHang on a minuteI'm not done talkingRegardsOh OK期望的结果:My name is blah blah blahNice to meet youPS: 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' 处结束搜索?
1 回答
慕的地10843
TA贡献1785条经验 获得超8个赞
重复*器是贪心的,它尽可能多地匹配直到\n\n(这是字符串中的最后一次出现)。在它后面放一个问号以使其不贪婪,以便它尽可能少地匹配:直到它匹配的第一次出现\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
添加回答
举报
0/150
提交
取消