Python正则表达式检测多行中的字符串

Python正则表达式检测多行中的字符串,python,regex,python-2.7,Python,Regex,Python 2.7,我试图检测一个字符串,有时显示为一行,有时显示为多行 案例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 i

我试图检测一个字符串,有时显示为一行,有时显示为多行

案例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)
使用以下正则表达式:

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

用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'

希望这有帮助

您需要在第二个字符串上匹配什么内容?测试失败。xx失败或xx错误是否有任何原因说明
\d+失败|\d+错误
不够?