我只想替换传递给re.sub
的正则表达式的部分([^\d+]
只是为了确保在此之后没有数字,即整数(包含所有数字) )被捕获)。但是,下面的代码替换下一个字符(即在第一个例子中吞下下一个“”)。
import re
pattern = r'foo-%d[^\d+]'
k = 12 # only substitute entire "foo-12" occurrences
result = re.sub(pattern % k, '@foo-%d@' % k, 'dasds foo-12 gfd9843')
# got: result == 'dasds @foo-12@gfd9843'
assert result == 'dasds @foo-12@ gfd9843', result
k = 1 # only substitute entire "foo-1" occurrences
result = re.sub(pattern % k, '@foo-%d@' % k, 'dasds foo-12 gfd9843')
assert result == 'dasds foo-12 gfd9843', result
k = 1 # only substitute entire "foo-1" occurrences
result = re.sub(pattern % k, '@foo-%d@' % k, 'dasds foo-11 gfd9843')
assert result == 'dasds foo-11 gfd9843', result
我该如何解决这个问题?我是否至少与正则表达式在正确的轨道上?
答案 0 :(得分:0)
在这里使用\b
import re
k = 12 # only substitute entire "foo-12" occurrences
s = 'dasds foo-12 gfd9843'
result = re.sub(r'foo-%d\b' % k, '@foo-%d@' % k, s)
# got: result == 'dasds @foo-12@gfd9843'
assert result == 'dasds @foo-12@ gfd9843', result
k = 1 # only substitute entire "foo-1" occurrences
result = re.sub(r'foo-%d\b' % k, '@foo-%d@' % k, s)
assert result == 'dasds foo-12 gfd9843', result