Biorąc pod uwagę następujący wzór tekstu,Python - pojedynczy vs wielowierszowego REGEX
#goals: timestamp raportu proces, np. 2011-09-21 15:45:00 i pierwsze dwie statystyki w succ. statystyka linii, np:
input_text = '''
# Process_Name (23387) Report at 2011-09-21 15:45:00.001 Type: Periodic #\n
some line 1\n
some line 2\n
some other lines\n
succ. statistics | 1438 1439 99 | 3782245 3797376 99 |\n
some lines\n
Process_Name (23387) Report at 2011-09-21 15:50:00.001 Type: Periodic #\n
some line 1\n
some line 2\n
some other lines\n
succ. statistics | 1436 1440 99 | 3782459 3797523 99 |\n
repeat the pattern several hundred times...
'''
mam to działa podczas iteracji linii do linii,
def parse_file(file_handler, patterns):
results = []
for line in file_handler:
for key in patterns.iterkeys():
result = re.match(patterns[key], line)
if result:
results.append(result)
return results
patterns = {
'report_date_time': re.compile('^# Process_Name\s*\(\s*\d+\) Report at (.*)\.[0-9] {3}\s+Type:\s*Periodic\s*#\s*.*$'),
'serv_term_stats': re.compile('^succ. statistics \|\s+(\d+)\s+ (\d+)+\s+\d+\s+\|\s+\d+\s+\d+\s+\d+\s+\|\s*$'),
}
results = parse_file(fh, patterns)
powrocie
[('2011-09-21 15:40:00',),
('1425', '1428'),
('2011-09-21 15:45:00',),
('1438', '1439')]
ale o listę wyjściu krotek jak mój bramka,
[('2011-09-21 15:40:00','1425', '1428'),
('2011-09-21 15:45:00', '1438', '1439')]
Próbowałem kilka combosów z pierwszych wzorów i leniwe kwantyfikatorem między nimi, ale nie można dowiedzieć się, jak uchwycić wzorów przy użyciu regex wielowierszowego
# .+? Lazy quantifier "match as few characters as possible (all characters allowed) until reaching the next expression"
pattern = '# Process_Name\s*\(\s*\d+\) Report at (.*)\.[0-9]{3}\s+Type:\s*Periodic.*?succ. statistics) \|\s+(\d+)\s+(\d+)+\s+\d+\s+\|\s+\d+\s+\d+\s+\d+\s+\|\s'
regex = re.compile(pattern, flags=re.MULTILINE)
data = file_handler.read()
for match in regex.finditer(data):
results = match.groups()
W jaki sposób można to osiągnąć?
nie mam dla ciebie odpowiedź, ale dlaczego osadzanie \ n w ciąg multi-line takiego? Rzeczywiste znaki nowego wiersza to znaki nowej linii. – geoffspear
Prawy Wooble, to jest w Linuksie, więc po prostu dodałem je do wyrażenia znaku nowej linii (starając się uniknąć zwykłego jest to \ n lub \ r lub \ r \ n?) –