在python中使用reg ex捕获多行

时间:2019-10-10 13:44:30

标签: python regex

我想编写一个捕获“ my_code”行和仅缩进两行的正则表达式

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

我正在使用my_code\n\s\s(.+)

my_code
  //abs[matches(@class,"her")] 
  //abs[matches(@class,"him")]
xxxx   //time
xxxxx   //h1

我正在使用my_code\n\s\s(.+)

my_code
  //abs[matches(@class,"her")] 
  //abs[matches(@class,"him")]
xxxx   //time
xxxxx   //h1

2 个答案:

答案 0 :(得分:0)

\s匹配一个空格和一个换行符。

为确保缩进,可以使用字符类匹配2倍换行符和1个或更多空格或制表符[\t ]+

^my_code\r?\n[\t ]+.+\r?\n[ \t]+.+
  • ^字符串的开头
  • my_code\r?\n匹配后按换行符
  • [\t ]+匹配1个以上空格或制表符
  • .+匹配除换行符之外的任意字符1倍以上
  • \r?\n[ \t]+.+再次匹配换行符,1个以上的空格或制表符以及除换行符以外的所有字符

Regex demo

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

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

Regex demo

答案 1 :(得分:0)

我设法使它像这样工作:

[:alpha:]

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()) 表示匹配除换行符之外的所有字符,并且这些字符应包含1个或多个。产生如下输出:

[^\n]+