[英]multi-line regex with groups python
looking for some assistance from regex experts for my below requirement. 寻求正则表达专家的一些帮助,以满足我的以下要求。 I have a string of the format
我有一个格式的字符串
if (x==True) then
operation1
end
if (y==False) then
operation2
operation3
end
if (z==1) then
operation4
end
I'm looking for this multiline string to be divided into groups as below. 我正在寻找这个多行字符串,如下所示分组。
('x==True', 'operation1')
('y==False', 'operation2', 'operation3')
('z==1', 'operation4')
Try this regex: 试试这个正则表达式:
if\s+\(([^)]+)\)\s+then\s+([\s\S]+?)end
reg = r"if\s+\((.*?)\)\s+then\s(.*?)end"
match = re.findall(reg, text, re.DOTALL)
A funny way with the parse module: 一个有趣的方式与解析模块:
import re
from parse import *
s='''if (x==True) then
operation1
end
if (y==False) then
operation2
operation3
end
if (z==1) then
operation4
end'''
for block in re.split(r'(?<=\nend)\n', s):
m = parse("if ({}) then\n{}\nend", block)
print(tuple([m[0]]+m[1].strip().split()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.