Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 多行正则表达式_Python_Regex_Python 2.7 - Fatal编程技术网

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)