Python 多行正则表达式
我制作了这个正则表达式Python 多行正则表达式,python,regex,python-2.7,Python,Regex,Python 2.7,我制作了这个正则表达式((\s\s\s.*\s)*)。这意味着,3个空格或制表符,之后是一些字符和一个空格、一个制表符或一行末尾。 如何将我得到的每一行存储到列表中 所以,如果我有这样的东西: ___The rabbit caught the lion\n ___The tiger got the giraffe\n ___The owl hit the man\n list=[The rabbit caught the lion, The tiger got the giraffe, The
((\s\s\s.*\s)*)
。这意味着,3个空格或制表符,之后是一些字符和一个空格、一个制表符或一行末尾。
如何将我得到的每一行存储到列表中
所以,如果我有这样的东西:
___The rabbit caught the lion\n
___The tiger got the giraffe\n
___The owl hit the man\n
list=[The rabbit caught the lion, The tiger got the giraffe, The owl hit the man]
输出如下所示:
___The rabbit caught the lion\n
___The tiger got the giraffe\n
___The owl hit the man\n
list=[The rabbit caught the lion, The tiger got the giraffe, The owl hit the man]
我要提到的是,我对其他每种模式都使用组 看起来您只想匹配一整行,从三个空格(或制表符)开始;这可以通过
re.MULTILINE
和^
和$
锚来完成
matches = re.findall('^\s{3}(.*)$', contents, re.MULTILINE)
如果您不关心在三个空格之前有字符,可以将表达式简化为:
matches = re.findall('\s{3}(.*)', contents)
这是因为
会将所有内容匹配到一个换行符(默认)。看起来您只想匹配一整行,从三个空格(或制表符)开始;这可以通过re.MULTILINE
和^
和$
锚来完成
matches = re.findall('^\s{3}(.*)$', contents, re.MULTILINE)
如果您不关心在三个空格之前有字符,可以将表达式简化为:
matches = re.findall('\s{3}(.*)', contents)
这是因为
会将所有内容匹配到一个换行符(默认)。你听说过str.splitlines
?正则表达式的组是否返回字符串?re.findall('\s{3}(.*),text)
@JBernardo该表达式至少应该锚定到行的开头。@Jack是的,但是如果所有的行都有3个空格,你就不需要了。$
肯定是不需要的(除非你使用DOTALL)你听说过str.splitlines
?正则表达式的组是否返回字符串?re.findall('\s{3}(.*),text)
@JBernardo该表达式至少应该锚定到行的开头。@Jack是的,但是如果所有行都有3个空格,你就不需要了。当然不需要$
(除非您使用DOTALL)