让我们定义你的字符串:
>>> s = "#big and #small, #big-red, #big-red-car and #big"
Run Code Online (Sandbox Code Playgroud)
现在,让我们做你的替换:
>>> import re
>>> re.sub(r'#big([.,\s]|$)', r'#BIG\1', s)
'#BIG and #small, #big-red, #big-red-car and #BIG'
Run Code Online (Sandbox Code Playgroud)
正则表达式#big([.,\s]|$)将匹配所有#big字符串,后跟句点,逗号,空格或行尾.如果您认为其他字符后可以接受#big,则应将它们添加到正则表达式中.
如果我们想要有点发烧友,我们可以使用前瞻性断言(?=...),以确保接下来的内容#big是可以接受的:
>>> re.sub(r'#big(?=[.,\s]|$)', r'#BIG', s)
'#BIG and #small, #big-red, #big-red-car and #BIG'
Run Code Online (Sandbox Code Playgroud)
为了测试这个工程时,根据需要#big具有"后,一个逗号或句号",让我们创建一个新的字符串:
>>> s = "#big and #big, #big. #small, #big-red, #big-red-car and #big"
Run Code Online (Sandbox Code Playgroud)
而且,让我们测试一下:
>>> re.sub(r'#big(?=[.,\s]|$)', r'#BIG', s)
'#BIG and #BIG, #BIG. #small, #big-red, #big-red-car and #BIG'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1498 次 |
| 最近记录: |