为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

人到中年有点甜 2023-03-16 15:55:08
细绳: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


查看完整回答
反对 回复 2023-03-16
  • 1 回答
  • 0 关注
  • 59 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信