带组的多行正则表达式 python
multi-line regex with groups python
为我的以下要求寻求正则表达式专家的帮助。我有一个格式为
的字符串
if (x==True) then
operation1
end
if (y==False) then
operation2
operation3
end
if (z==1) then
operation4
end
我正在寻找这个多行字符串,如下所示进行分组。
('x==True', 'operation1')
('y==False', 'operation2', 'operation3')
('z==1', 'operation4')
试试这个正则表达式:
if\s+\(([^)]+)\)\s+then\s+([\s\S]+?)end
描述
演示
reg = r"if\s+\((.*?)\)\s+then\s(.*?)end"
match = re.findall(reg, text, re.DOTALL)
parse 模块的有趣方式:
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()))
为我的以下要求寻求正则表达式专家的帮助。我有一个格式为
的字符串if (x==True) then
operation1
end
if (y==False) then
operation2
operation3
end
if (z==1) then
operation4
end
我正在寻找这个多行字符串,如下所示进行分组。
('x==True', 'operation1')
('y==False', 'operation2', 'operation3')
('z==1', 'operation4')
试试这个正则表达式:
if\s+\(([^)]+)\)\s+then\s+([\s\S]+?)end
描述
演示
reg = r"if\s+\((.*?)\)\s+then\s(.*?)end"
match = re.findall(reg, text, re.DOTALL)
parse 模块的有趣方式:
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()))