Python 如何使用regex解决这个问题?
鉴于该字符串: \n \n text1\n \ttext2\n Message: 1st message\n some more text\n \n \n Message: 2dn message\n\n \t\t Message: 3rd message\n text3\n \n \n 文本1\n \ttext2\n 消息:第一条消息\n 更多文本\n \n \n 消息:2dn消息\n\n \t\t 消息:第三条消息\n text3\n 我想从多行字符串中提取消息(标记为“Message:”。我应该使用什么正则表达式来捕获这3个组:Python 如何使用regex解决这个问题?,python,regex,Python,Regex,鉴于该字符串: \n \n text1\n \ttext2\n Message: 1st message\n some more text\n \n \n Message: 2dn message\n\n \t\t Message: 3rd message\n text3\n \n \n 文本1\n \ttext2\n 消息:第一条消息\n 更多文本\n \n \n 消息:2dn消息\n\n \t\t 消息:第三条消息\n text3\n 我想从多行字符串中提取消息(标记为“Messag
- 第1组:“第一条消息”
- 第2组:“2dn消息”
- 第3组:“第3条消息”
'^'
在字符串开头和每行开头(紧跟在每一换行之后)匹配;模式字符“$”
在字符串末尾和每行末尾(紧靠每一换行之前)匹配。默认情况下,“^”
仅在字符串开头匹配,“$”
仅在字符串末尾和字符串末尾的换行符(如果有)之前匹配
(.+?)$
至少匹配一个字符,直到字符串最接近的结尾
编辑:实际上,简单版本也可以:
>>> re.findall('Message: (.+)', s)
['1st message', '2dn message', '3rd message']
我很惊讶它不在你尝试过的众多事情中:)@OP,你不需要正则表达式。假设您不关心消息“”后面的行
您不喜欢下一行的
更多文本和文本部分吗?张贴您的注册表更正;我只希望内容与“Message:”相同,如果这是他想要的,为什么不只是re.findall(“Message:(.+)”,s)?我对regex完全陌生,我走错了方向。首先,我尝试使用match
,而不是findall
(我不确定每一个都做了什么,但我会详细阅读)。出于某种原因,我认为我必须在表达式的开头使用通配符。@Sly:findall
类似于search
,而不是match
,只是它在找到匹配项后不会停止,而是继续尝试匹配更多内容,并累积列表中的所有内容<代码>匹配
仅从字符串开头开始搜索。不,您不必在字符串的开头使用通配符。
>>> re.findall('Message: (.+)', s)
['1st message', '2dn message', '3rd message']
for line in mystring.split("\n")
if "Message:" in line:
print "found: ",line