用字符串替换整数的间隔

时间:2018-05-08 14:21:57

标签: python regex

我想用数据中的字符串test替换100到200之间的所有整数。以下是一些控制案例:

`this is a control 150` = `this is a control test`
`this is a control 160` = `this is a control test`
`this is a control 150000` = `this is a control 150000`

我的想法是使用正则表达式,我有以下内容:re.sub("\d", "test", "this is a control 150")

但是,这会用test替换所有整数。有没有办法将它限制为仅替换100-200?

2 个答案:

答案 0 :(得分:-1)

使用re.search

<强>演示:

import re
s = ["this is a control 150", "this is a control 160", "this is a control 160.05", "this is a control 150000"]
for i in s:
    m = re.search("\d+\.?\d*", i)
    if m:
        if 100 < float(m.group()) < 200:
            print(i.replace(m.group(0), "test"))
        else:
            print(i)

<强>输出:

this is a control test
this is a control test
this is a control test
this is a control 150000

答案 1 :(得分:-1)

如果您的字符串很简单,您可能需要考虑拆分它们,解析int,比较和替换。

for line in your_lines:
    num = int(line.split("control ")[1])
    if num > 100 and num < 200:
         line.replace(str(num), 'test')