Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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中使用reg-ex捕获多行_Python_Regex - Fatal编程技术网

在python中使用reg-ex捕获多行

在python中使用reg-ex捕获多行,python,regex,Python,Regex,我想写一个正则表达式,它捕获“my_code”行和在它下面缩进的两行 //abs[matches(@class,"her")] //abs[matches(@class,"him")] 我正在使用myu-code\n\s\s(+) 我正在使用myu-code\n\s\s(+) \s匹配空格和换行符 为了确保它是indentend,可以使用字符类匹配换行符的2倍和1个或多个空格或制表符[\t]+ ^my_code\r?\n[\t ]+.+\r?\n[ \t]+.+ ^字符串的开头 my

我想写一个正则表达式,它捕获“my_code”行和在它下面缩进的两行

//abs[matches(@class,"her")] 
  //abs[matches(@class,"him")]
我正在使用
myu-code\n\s\s(+)

我正在使用
myu-code\n\s\s(+)


\s
匹配空格和换行符

为了确保它是indentend,可以使用字符类匹配换行符的2倍和1个或多个空格或制表符
[\t]+

^my_code\r?\n[\t ]+.+\r?\n[ \t]+.+
  • ^
    字符串的开头
  • my\u code\r?\n
    按字面意思匹配,后跟换行符
  • [\t]+
    匹配1+个空格或制表符
  • +
    匹配除换行符以外的任何字符的1+倍
  • \r?\n[\t]+.+
    再次匹配换行符、1+空格或制表符以及除换行符以外的任何字符

要匹配缩进部分1次或多次,可以重复非捕获组并使用量词
+

^my_code(?:\r?\n[\t ]+.+)+

\s
匹配空格和换行符

为了确保它是indentend,可以使用字符类匹配换行符的2倍和1个或多个空格或制表符
[\t]+

^my_code\r?\n[\t ]+.+\r?\n[ \t]+.+
  • ^
    字符串的开头
  • my\u code\r?\n
    按字面意思匹配,后跟换行符
  • [\t]+
    匹配1+个空格或制表符
  • +
    匹配除换行符以外的任何字符的1+倍
  • \r?\n[\t]+.+
    再次匹配换行符、1+空格或制表符以及除换行符以外的任何字符

要匹配缩进部分1次或多次,可以重复非捕获组并使用量词
+

^my_code(?:\r?\n[\t ]+.+)+

我设法让它像这样工作:

test_str  = """ 
    my_code
      //abs[matches(@class,"her")] 
      //abs[matches(@class,"him")]
    xxxx   //time
    xxxxx   //h1
"""
pattern = re.compile('my_code\n\s+[^\n]+\n\s+[^\n]+')
res = re.search(pattern, test_str)
print(res.group())
[^\n]+
表示匹配除新行以外的每个字符,并且应该有一个或多个字符。这将产生如下输出:

my_code
      //abs[matches(@class,"her")] 
      //abs[matches(@class,"him")]

我设法让它像这样工作:

test_str  = """ 
    my_code
      //abs[matches(@class,"her")] 
      //abs[matches(@class,"him")]
    xxxx   //time
    xxxxx   //h1
"""
pattern = re.compile('my_code\n\s+[^\n]+\n\s+[^\n]+')
res = re.search(pattern, test_str)
print(res.group())
[^\n]+
表示匹配除新行以外的每个字符,并且应该有一个或多个字符。这将产生如下输出:

my_code
      //abs[matches(@class,"her")] 
      //abs[matches(@class,"him")]