Регулярное выражение Python против 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=43583 cost=72 Оценка: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)

В чем разница между настройками regex101 и пакетом Python re? Или они одинаковые? У них разные флаги или настройки/что-то еще?

Почему в Python нет сопоставления с образцом?


person alvas    schedule 19.04.2017    source источник
comment
вы, вероятно, хотите, чтобы re.search, re.match возвращало совпадение только в том случае, если оно появляется в начале вашей строки   -  person Anthony Sottile    schedule 19.04.2017
comment
Арх... re.findall(pattern, x)[0]   -  person alvas    schedule 19.04.2017
comment
Фактически, вот сгенерированный код: regex101.com/r/Hwxsib/ 1/codegen?language=python   -  person Anthony Sottile    schedule 19.04.2017
comment
О, круто! Не понял функцию в regex101!   -  person alvas    schedule 19.04.2017


Ответы (2)


Вероятно, вы хотите, чтобы re.search, re.match возвращало совпадение только в том случае, если оно появляется в начале вашей строки.

regex101 также показывает используемый код: https://regex101.com/r/Hwxsib/1/codegen?language=python

Из кода regex101 вот что он делает (скопировано и отредактировано для краткости):

import re

regex = r"..."

test_str = "..."

matches = re.finditer(regex, test_str)

...
person Anthony Sottile    schedule 19.04.2017

Вы хотите использовать re.search. match будет возвращаться только в том случае, если совпадение находится в начале строки!

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)
person Christopher Apple    schedule 19.04.2017