Python regex用于检测多行中的字符串

2024-10-17 06:12:54 发布

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

我试图检测一个字符串,有时它显示为一行,有时它显示为多行。你知道吗

案例1:

==================== 1 error in 500.14 seconds =============

案例2:

 ================= 3 tests deselected by "-m 'not regression'" ==================
 21 failed, 553 passed, 35 skipped, 3 deselected, 4 error, 51 rerun in 6532.96 seconds

我试过下列方法,但不起作用

==+.*(?i)(?m)(error|failed).*(==+|seconds)

Tags: 方法字符串inrerunbynottestserror
1条回答
网友
1楼 · 发布于 2024-10-17 06:12:54

使用以下正则表达式:

==+[\s\S]*?(\d+)\s(error|failed).*(==+|seconds)
  • [\s\S]而不是.也允许使用行分隔符
  • (\d+)是第一个匹配的组,因此matches[0]将始终包含数字,如1或21
  • (error|failed)是第二个匹配组,因此matches[1]将包含“error”或“failed”

Regex101 Demo

Python测试:

import re

pattern = "==+[\s\S]*?(\d+)\s(error|failed).*(==+|seconds)"
case1 = "==================== 1 error in 500.14 seconds ============="
p = re.compile(pattern)
matches = p.match(case1).groups()
matches[0] + " " + matches[1]   # Output: '1 error'

case2 = """================= 3 tests deselected by -m 'not regression' ==================
 21 failed, 553 passed, 35 skipped, 3 deselected, 4 error, 51 rerun in 6532.96 seconds"""
matches = p.match(case2).groups()
matches[0] + " " + matches[1]   # Output: '21 failed'

希望这有帮助!你知道吗

相关问题 更多 >