如何通过正则表达式提取命令输出中的GFAF_XXX格式内容并存为列表
Solution to Extract GFAF_XXX into a List
Hey Damian, I've got you covered! Let's break down two straightforward ways to get the exact list you want, including the regex approach you were trying.
1. Command-Line Method (Quick & Dirty)
Since your command output has the target strings as the third field in each data line, you can use common shell tools to extract and format them directly:
# Assuming your command output is saved in process_output.txt awk '{if(NR>1) print $3}' process_output.txt | tr '\n' ',' | sed 's/,$//' | sed 's/^/[/;s/$/]/'
awk '{if(NR>1) print $3}': Skips the header line and pulls the 3rd column from each data rowtr '\n' ',': Replaces newlines with commas to string values togethersed 's/,$//': Removes the trailing comma that would otherwise clutter the endsed 's/^/[/;s/$/]/': Wraps the final string in square brackets to match your desired format
This will output exactly: [GFAF_0,GFAF_235,GFAF_1]
2. Python Script with Regex (More Flexible)
If you want to use regex (the approach you initially tried), the correct pattern to match GFAF_XYZ (where XYZ is one or more digits) is GFAF_\d+. Here's a complete, working script:
import re # Paste your command output here as a string process_output = """Process Pid Mello No Status 122 523 GFAF_0 1 Running 125 512 GFAF_235 2 Running 128 987 GFAF_1 3 Stopped""" # Extract all matches using regex matches = re.findall(r'GFAF_\d+', process_output) # Format into the list string you need result = f"[{','.join(matches)}]" print(result) # Output: [GFAF_0,GFAF_235,GFAF_1]
r'GFAF_\d+': Let's break down the regex pattern:GFAF_: Matches the exact fixed prefix of your target strings\d+: Matches one or more digits (covers single-digit values like0and multi-digit ones like235)
re.findall(): Scans the entire input string and pulls out all non-overlapping matches automatically
Why Your Earlier Regex Might Have Failed
If you weren't getting matches before, common pitfalls include:
- Forgetting the
+after\d(this only matches a single digit instead of multiple) - Accidentally adding extra characters (like a stray space or incorrect underscore)
- Using a regex function that only checks the start/end of the string instead of searching the entire text
内容的提问来源于stack exchange,提问作者demien
相关产品推荐
相关产品推荐

