簡體   English   中英

正則表達式不能替換以“。”開頭或以“ +”結尾的單詞,例如“ .NET”或“ C ++”

[英]regex not replacing word starting with “.” or ending with “+” like “.NET” or “C++”

我試圖取代'.net''i like .net'.NET 預期輸出: 'i like .NET'.

Cpp'i like c++' 'c++'中的'i like c++' 預期輸出: '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

之前的\\b . 在之前需要一個字符char . \\b\\. 將匹配一個. ASP.NET ,但不在In .NET

如果您想匹配整個單詞而不管搜索單詞開頭/結尾的字符是什么,最好的選擇是使用環視:

import re
regex_match = re.compile(r'(?<!\w){}(?!\w)'.format(re.escape('.net')))
print(regex_match.sub('NET', 'I like .net, not  my.net.'))
# => I like NET, not  my.net.

參見Python演示 如果您使用net而不是.net ,它將仍然工作相同(請參見另一個Python演示 )。

在此, (?<!\\w)將緊接搜索詞之前需要一個非單詞char或字符串開頭,而(?!\\w)將緊接該搜索詞之后要求一個非單詞char或字符串結尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM