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

如何用正则表达式仅替换数据中100-200的整数为test?

如何用正则表达式替换100-200之间的整数为"test"

你的问题很典型——刚开始写正则容易只考虑单个字符匹配,而忽略了要匹配整个范围内的完整数字。咱们一步步来解决:

问题分析

你原来的代码re.sub("\d", "test", "this is a control 150")会把每个数字字符都替换成"test",所以150会变成testtesttest,完全不符合需求。我们需要精准匹配100到200之间的完整整数,同时不碰超出范围的数字(比如150000)。

正确的正则表达式

要匹配100-200的整数,可以拆成两种情况:

  • 100到199:用1\d{2}匹配(以1开头,后跟任意两个数字)
  • 刚好200:直接写200

把这两种情况用|组合,再加上单词边界\b(确保匹配的是独立数字,不会误匹配长数字里的子串,比如1500里的150),最终的正则是:\b(1\d{2}|200)\b

完整代码示例

import re

def replace_target_numbers(input_text):
    # 使用r前缀定义原始字符串,避免转义问题
    return re.sub(r"\b(1\d{2}|200)\b", "test", input_text)

# 测试你的用例
print(replace_target_numbers("this is a control 150"))  # 输出: this is a control test
print(replace_target_numbers("this is a control 160"))  # 输出: this is a control test
print(replace_target_numbers("this is a control 150000"))  # 输出: this is a control 150000

# 额外测试边界情况
print(replace_target_numbers("100 should be replaced, 200 too, but 99 and 201 stay"))
# 输出: test should be replaced, test too, but 99 and 201 stay

关键细节解释

  • \b:单词边界,确保我们匹配的是独立的数字,比如不会把"1500"里的"150"误替换
  • 1\d{2}:精准匹配100-199的三位数
  • |:正则里的“或”操作符,用来合并两种匹配情况
  • 使用原始字符串r"":避免Python对反斜杠的转义处理,让正则表达式更易读

内容的提问来源于stack exchange,提问作者N08

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:13:17