在正则表达式python上的两个字符串之间拆分,但使用re.split包含在内,并返回列表

时间:2019-07-09 23:36:26

标签: python regex

我正在尝试将文本分割成如下格式的文件:

module 
some text
endmodule

module 
some other text
endmodule

在单词module和endmodule之间,并且仍然在输出字符串中包含module和endmodule。

这不是其他正则表达式问题的重复,因为我试图使用re.split()返回一个列表,但未找到。

这是我尝试过的正则表达式

s=file.read()
l=re.split("module(.*)endmodule",s)

但它不会分裂任何东西...

理想情况下,最终输出将是一个列表,其中包含两个模块均为字符串,

['module \ n sometext \ n endmodule','module \ n sometext \ n endmodule']

2 个答案:

答案 0 :(得分:1)

我的猜测是,您可能希望设计一个类似于以下内容的表达式:

module(.*?)endmodule

虽然不确定。

使用re.finditer进行测试

import re

regex = r"module(.*?)endmodule"

test_str = ("module \n"
    "some text\n"
    "endmodule\n\n"
    "module \n"
    "some other text\n"
    "endmodule")

matches = re.finditer(regex, test_str, re.DOTALL)

for matchNum, match in enumerate(matches, start=1):

    print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))

    for groupNum in range(0, len(match.groups())):
        groupNum = groupNum + 1

        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))

使用re.findall

进行测试
import re

regex = r"module(.*?)endmodule"

test_str = ("module \n"
    "some text\n"
    "endmodule\n\n"
    "module \n"
    "some other text\n"
    "endmodule")

print(re.findall(regex, test_str, re.DOTALL))

this demo的右上角对表达式进行了说明,如果您想进一步探索或简化/修改它,可以在this link中观察它如何与某些示例输入匹配如果愿意,可以逐步进行。

答案 1 :(得分:1)

我们可以使用正向后看和正向前看

print(re.split('(?<=endmodule)[.\n]*?(?=module)', s))

给予

['module\nsome text\nendmodule', 'module\nsome other text\nendmodule']

其中

s = ("module\n"
     "some text\n"
     "endmodule\n\n"
     "module\n"
     "some other text\n"
     "endmodule")