让我们定义你的字符串:
>>> s = "#big and #small, #big-red, #big-red-car and #big"
现在,让我们进行替换:
>>> import re
>>> re.sub(r'#big([.,\s]|$)', r'#BIG\1', s)
'#BIG and #small, #big-red, #big-red-car and #BIG'
正则表达式 #big([.,\s]|$)
将匹配所有后面跟着句号、逗号、空格或行尾的 #big
字符串。如果您认为其他字符在 #big
之后也是可接受的,您应该将它们添加到正则表达式中。
替代方案
如果我们想要更加高级一些,我们可以使用前瞻断言 (?=...)
来确保跟随 #big
的内容是可接受的:
>>> re.sub(r'#big(?=[.,\s]|$)', r'#BIG', s)
'#BIG and #small, #big-red, #big-red-car and #BIG'
使用句号和逗号的测试
为了测试当#big
后面有"逗号或句号"时,此方法是否按预期工作,让我们创建一个新字符串:
>>> s = "#big and #big, #big. #small, #big-red, #big-red-car and #big"
而且,让我们来测试一下:
>>> re.sub(r'#big(?=[.,\s]|$)', r'#BIG', s)
'#BIG and #BIG, #BIG. #small, #big-red, #big-red-car and #BIG'
str
的replace
方法即可。 - Vedang Mehta#big
在字符串末尾,或者在其后有逗号或句号,这种方法不会起作用,对吧? - Vicky Leong