如何格式化正则表达式

2024-04-29 00:33:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试发出一个警告,它可以在日志文件中查找已知的警告。你知道吗

在查看警告期间,将直接从日志文件复制文件中的警告。你知道吗

这里的任务是尽可能简单。但我发现直接复制有点问题,因为警告可能包含绝对路径。你知道吗

所以我添加了一个“标签”,可以插入到系统应该查找的警告中。整根绳子看起来像这样。你知道吗

WARNING:HDLParsers:817 - ":RE[.*]:/modules/top/hdl_src/top.vhd" Line :RE[.*]: Choice . is not a locally static expression.

标签是:RE[在这里插入RegEx]:。 在上面的警告字符串中有两个标签,我正试图使用python3regex工具找到它们。我的模式如下:

(:RE\[.*\]\:)

参见RegEx101以获取参考

上面提到的问题是,当字符串中有两个标记时,它只会发现一个从第一个标记扩展到最后一个标记的结果。如何设置regex以便找到每个标记?你知道吗

敬礼


Tags: 文件字符串标记resrcmodules警告top
1条回答
网友
1楼 · 发布于 2024-04-29 00:33:19

您可以将re.findall与下面的正则表达式一起使用,假定方括号内的正则表达式从:RE[],然后是]

:RE\[.*?]:

regex demo.*?匹配除换行符以外的0个或多个字符,但要尽可能少。见rexegg.com description of a lazy quantifier solution

The lazy .*? guarantees that the quantified dot only matches as many characters as needed for the rest of the pattern to succeed.

IDEONE demo

import re
p = re.compile(r':RE\[.*?]:')
test_str = "# Even more commments\nWARNING:HDLParsers:817 - \":RE[.*]:/modules/top/hdl_src/cpu_0342.vhd\" Line :RE[.*]: Choice . is not a locally static expression."
print(p.findall(test_str))

如果需要获取[]之间的内容,请使用捕获组,以便re.findall可以仅提取这些内容:

p = re.compile(r':RE\[(.*?)]:')

another demo

要获取索引,请使用^{}(请参见this demo):

re.finditer(pattern, string, flags=0)
Return an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match.

p = re.compile(r':RE\[(.*?)]:')
print([x.start(1) for x in p.finditer(test_str)])

相关问题 更多 >