Python 正则表达式与 Regex101

Python regex vs Regex101

输入字符串:

I0419 01:52:16.606123 136 TrainerInternal.cpp:181] Pass=15 Batch=74 samples=3670 AvgCost=263.331 Eval: classification_error_evaluator=0.970178 I0419 01:52:16.815407 136 Tester.cpp:115] Test samples=458 cost=203.737 Eval: classification_error_evaluator=0.934446

模式:

Pass=([0-9]+).*classification_error_evaluator=(0.[0-9]+).*classification_error_evaluator=(0.[0-9]+)

期望的输出:

(15, 0.970178, 0.934446)

并且在 Regex101(https://regex101.com/r/Hwxsib/1) 上,我似乎捕捉到了正确的模式。

但在 Python 中,它与组不匹配,它什么也没抓到:

import re

x = "I0419 01:52:16.606123   136 TrainerInternal.cpp:181]  Pass=15 Batch=74 samples=3670 AvgCost=263.331 Eval: classification_error_evaluator=0.970178 I0419 01:52:16.815407   136 Tester.cpp:115]  Test samples=458 cost=203.737 Eval: classification_error_evaluator=0.934446"

pattern = "Pass=([0-9]+).*classification_error_evaluator=(0\.[0-9]+).*classification_error_evaluator=(0\.[0-9]+)"

re.match(pattern, x)

与 Python re 包相比,regex101 设置有何不同?还是它们相同?它们有不同的标志还是settings/something?

为什么 Python 中的模式不匹配?

您想使用 re.searchmatch 只会 return 如果匹配在字符串的开头!

import re

x = "I0419 01:52:16.606123   136 TrainerInternal.cpp:181]  Pass=15 Batch=74 samples=3670 AvgCost=263.331 Eval: classification_error_evaluator=0.970178 I0419 01:52:16.815407   136 Tester.cpp:115]  Test samples=458 cost=203.737 Eval: classification_error_evaluator=0.934446"

pattern = r'Pass=([0-9]+).*classification_error_evaluator=(0\.[0-9]+).*classification_error_evaluator=(0\.[0-9]+)'

print re.search(pattern, x).groups(1)

您可能想要 re.searchre.match 只有 return 出现在字符串开头的匹配项

regex101 还向您展示了它使用的代码:https://regex101.com/r/Hwxsib/1/codegen?language=python

来自 regex101 代码,这是它正在做的事情(为简洁起见复制和编辑):

import re

regex = r"..."

test_str = "..."

matches = re.finditer(regex, test_str)

...