Python中如何用正则表达式批量替换带数字的特定字符串?
Yes, you absolutely can use regular expressions in Python to handle this kind of replacement without maintaining a huge dictionary of terms. This is exactly the sort of pattern-matching task regex was built for.
How It Works
The core idea is to target any sequence of letters followed immediately by one or more digits, then insert a space between the two parts. Here's the breakdown:
([a-zA-Z]+): Captures one or more uppercase/lowercase letters (this covers your "block", "sector", "phase" and any similar terms)(\d+): Captures one or more digits (the number trailing the word)- We replace the matched pattern with
\1 \2, where\1refers to the captured letter group and\2refers to the captured digit group—with a space in between.
Python Code Example
import re def add_space_between_word_and_number(text): # Regex pattern to match letter sequences followed by digits regex_pattern = r'([a-zA-Z]+)(\d+)' # Replace with the letter group, a space, then the digit group return re.sub(regex_pattern, r'\1 \2', text) # Test with your sample cases sample_input = "Replace block1, sector2, phase3, pocket4 and even randomword123 here." formatted_output = add_space_between_word_and_number(sample_input) print(formatted_output)
Output:
Replace block 1, sector 2, phase 3, pocket 4 and even randomword 123 here.
Quick Customization Tip
If your terms might include special characters like underscores (_) or hyphens (-), you can tweak the regex to include them:
# Handle words with underscores/hyphens regex_pattern = r'([a-zA-Z_-]+)(\d+)'
This approach automatically handles any term that fits the "letters + digits" structure—no need to update a dictionary every time you encounter a new term.
内容的提问来源于stack exchange,提问作者iam.Carrot

