Python正则提取测试日志中指定首尾模式的内容(含首尾)
Let's fix your script to correctly pull the log segments you need—including both the full start line (from --- /b/act-builder/sandboxes/ through Linux ---) and the Error code end marker, while supporting multiple matches across the entire log file.
What Was Wrong With Your Original Code
Your approach had two critical gaps:
- The regex only captured content after
/b/act-builder/(thanks to the capturing group(.*?)), so it cut off the full start line and excluded theError codemarker entirely. - It didn't account for the
Linux ---suffix that ends your target starting line.
Corrected Solution
Here's a revised script that fixes these issues and follows Python best practices for file handling:
import re # Use a `with` statement to safely open/close the file automatically with open('atf_log_28378.txt', 'r') as file: log_content = file.read() # Regex pattern tailored to your requirements: # - Matches lines starting with your exact prefix # - Includes all content up to and including "Error code" # - Works across multiple lines pattern = r'^--- /b/act-builder/sandboxes/.*?Linux ---.*?Error code' matched_segments = re.findall(pattern, log_content, re.MULTILINE | re.DOTALL) # Print each matched segment with a clear label for count, segment in enumerate(matched_segments, 1): print(f'Failed Test Case #{count}:\n{segment}\n')
Regex Breakdown
Let's break down why this pattern works:
^--- /b/act-builder/sandboxes/: Explicitly matches the start of a line with your required prefix (the^works withre.MULTILINEto target every line start, not just the top of the file).*?Linux ---: Non-greedily grabs all content until it hits theLinux ---end of your starting line.*?Error code: Non-greedily captures everything between the start line and theError codemarker, including newlines (thanks tore.DOTALL)re.MULTILINE | re.DOTALL: Combined flags let the regex handle line breaks and multi-line segments correctly
Example Output
For your sample input line:
--- /b/act-builder/sandboxes/ACT-SB-RELEASE_174_THROTTLE-28378/src/junos/usr.sbin/rpd/lib/policy/atf-tests.host,linux --- *** [atf-run.log] Error code
The script will output:
Failed Test Case #1: --- /b/act-builder/sandboxes/ACT-SB-RELEASE_174_THROTTLE-28378/src/junos/usr.sbin/rpd/lib/policy/atf-tests.host,linux --- *** [atf-run.log] Error code
If your log has multiple matching segments, each will be printed as a separate labeled entry.
内容的提问来源于stack exchange,提问作者om tripathi

