首页 > 解决方案 > 当字符串是模式时,Python替换单词而不是单词的一部分

问题描述

我有这样的单词模式: *_you_don't_* think_you_don't_* you_don't_*_* you_don't_know_your_youth

我只想在它是一个词而不是当它是这个词的一部分时用“我们”替换这个词。

我尝试过使用单词边界功能,但这仅在将文本分成单词时才有效,在我的情况下,模式是使用下划线、星号等形成的

import re
s = "*_you_don't_* think_you_don't_* you_don't_*_* you_don't_know_your_youth"
re.sub(r'\you\b', 'we', s)

在上面的示例中,我希望单词看起来像这样: *_we_don't_* think_we_don't_* we_don't_*_* we_don't_know_your_youth

并且使用代码,我写道我无法达到那个结果。

标签: pythonregex

解决方案


[a-zA-Z] - Matches anything that is a single character

![a-zA-Z] - Anything that is not a single English character

? - One or zero match of pattern

(?<![a-zA-Z])you(?![a-zA-Z]) - This matches "you" if not preceded and 
not followed by a letter

代码:

import re
s = "*_you_don't_* think_you_don't_* you_don't_*_* you_don't_know_your_youth"
print re.sub(r'(?<![a-zA-Z])you(?![a-z-Z])', 'we', s)

输出:

*_we_don't_* think_we_don't_* we_don't_*_* we_don't_know_your_youth

演示


推荐阅读