Python中如何移除字符串内指定模式列表元素并提取目标数字
Hey there! Let's solve this problem in two practical ways—one that cuts out the intermediate "remove patterns" step entirely (it's more efficient), and another that works with the list of patterns you already have.
Instead of first hunting for patterns to remove, we can split the original string using . or - (with optional surrounding spaces) as separators. Then we just need to collect all the numbers from the resulting segments.
Here's the code:
import re original_string = "01. 01 22 3 456 0001 02 . 002 3. 0003 4 . 0004 05- 0005 06 - 0006 7- 0007 8 - 0008 09. 0009 10. 0010" # Split the string using ./- (with optional spaces around) as separators split_segments = re.split(r'\s*(?:\.|\-)\s*', original_string) # Skip the first empty segment, then split each part into numbers and flatten the list target_numbers = [] for segment in split_segments[1:]: target_numbers.extend(segment.strip().split()) print(target_numbers)
This will output exactly the list you want:['01', '22', '3', '456', '0001', '002', '0003', '0004', '0005', '0006', '0007', '0008', '0009', '0010']
If you want to work with the list of patterns you already identified, we'll need to escape special characters (like ., which has meaning in regex) and then replace all those patterns with empty strings. Finally, we split and clean up the remaining text.
Here's how to do it:
import re original_string = "01. 01 22 3 456 0001 02 . 002 3. 0003 4 . 0004 05- 0005 06 - 0006 7- 0007 8 - 0008 09. 0009 10. 0010" remove_patterns = ['01.', '02 .', '3.', '4 .', '09.', '10.', '05-', '06 -', '7-', '8 -'] # Escape special characters in each pattern to avoid regex mismatches escaped_patterns = [re.escape(pattern) for pattern in remove_patterns] # Combine all patterns into a single regex combined_regex = '|'.join(escaped_patterns) # Remove all matching patterns from the original string cleaned_string = re.sub(combined_regex, '', original_string) # Split by spaces and filter out any empty strings target_numbers = [num for num in cleaned_string.split() if num] print(target_numbers)
This will also produce your desired output.
Quick Notes:
- The first method is cleaner and avoids needing to pre-define remove patterns—great if you don't want to manually list those segments.
- The second method is useful if you already have the remove patterns ready, just remember to escape special regex characters (like
.) to prevent unintended matches.
内容的提问来源于stack exchange,提问作者samu101108

