You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何用正则表达式批量替换带数字的特定字符串?

Absolutely Feasible—Regex Is Perfect for This!

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 \1 refers to the captured letter group and \2 refers 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:32:44