python:替换/替换字符串中的所有全字匹配

Vic*_*ong 3 python regex string django

我们假设我的字符串是 "#big and #small, #big-red, #big-red-car and #big"

如何使用re.sub(), re.match(), etc.单词替换一个标签?

例如,所有的#bigs必须改为大,但#big-red#big-red-car不会受到影响.

Joh*_*024 6

让我们定义你的字符串:

>>> 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)