我正在尝试用 .NET 替换 'i like .net' 中的 '.net'。预期输出:'i like .NET'.
还有 'c++' 在 'i like c++' 和 Cpp。预期输出:'i like Cpp'.
像'c++'这样的特殊字符的情况比较多
import re
regex_match = re.compile(r'\bnet\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .NET Which works but I need boundary match also.
regex_match = re.compile(r'\b.net\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .net
regex_match = re.compile(r'\b\.net\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .net
regex_match = re.compile(r'\b' + re.escape('.net') + '\b')
print(regex_match.sub('NET', 'I like .net'))
# output I like .net
regex_match = re.compile(r'\b' + re.escape('.net') + '\b')
print(regex_match.sub('NET', 'I like \.net'))
# output I like \.net
print(re.sub(r'\b' + re.escape('.net') + '\b', '.NET', 'I like .net'))
# output I like .net
regex_match = re.compile(r'\b' + re.escape('.net') + '\b')
print(regex_match.sub('NET', re.escape('I like .net')))
# output I\ like\ \.net
更新:
regex_match = re.compile(r'\b' + re.escape('c++') + '\b')
print(regex_match.sub('cpp', 'I like c++'))
# output `I like c++` expected `I like cpp`
我经历了很多关于正则表达式替换的 stackoverflow 问题。到处都是它建议的转义'。',正如你在上面看到的那样,我试过了。仍然无法正常工作。非常感谢任何帮助。
请您参考如下方法:
不要将 \b(单词边界)放在点之前,因为点不是单词字符。
您可以使用:
>>> regex_match = re.compile(r'\.net\b')
>>> print(regex_match.sub('.NET', 'I like .net'))
I like .NET
编辑:
根据您的评论,您可能可以使用此正则表达式:
>>> print(re.sub(r'(^|\s)\.net(?=\s|$)', r'\1.NET', 'I like .net'))
I like .NET
>>> print(re.sub(r'(^|\s)\.net(?=\s|$)', r'\1.NET', 'I like.net'))
I like.net
