python - 当字符串是模式时,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
并且使用代码,我写道我无法达到那个结果。
解决方案
[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
推荐阅读
- memory-leaks - Pytorch:如何知道是否确实需要使用正在使用的 GPU 内存或是否存在内存泄漏
- c# - 如何使用 .NET 通用主机将 REST API 添加到用 .NET Framework 4.8 编写的控制台应用程序?
- ios - 您好,我正在使用 Collection View 单元格,我想记录其中有多少被单击“变为真”并返回下一个视图控制器
- ruby - 如何为每个 Enumerable 方法创建别名?
- r - R - 访问在函数参数中作为字符串传递的数据框列名
- javascript - 如何强制更新(重新渲染)React 组件?
- wso2 - Whatsapp otp 验证 wso2 是 5.10
- java - 单击时替换图像
- python - Selenium - 无法在动态元素中获取 xpath
- ansible - 如何使用 ANSIBLE 将多个主机的多个 stdout_lines 保存到一个 txt 文件?