【问题标题】:Python regex to detect string in multilinePython正则表达式检测多行中的字符串
【发布时间】:2017-05-08 10:36:17
【问题描述】:

我正在尝试检测一个字符串,有时它显示为一行,有时它显示为多行。

案例一:

==================== 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)

【问题讨论】:

  • 第二个字符串需要匹配什么内容?
  • 测试失败。 xx 失败xx 错误
  • \d+ failed|\d+ error 不够用吗?

标签: python regex python-2.7


【解决方案1】:

使用下面的正则表达式:

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

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'

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2010-12-04
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    相关资源
    最近更新 更多