您必須匹配不區分大小寫。 您可以在模式中包含的標誌,如:
import re
variants = ["I have apple.", "I have Apple.", "I have APPLE and aPpLe."]
def replace_apple_insensitive(s):
# Adding (?i) makes the matching case-insensitive
return re.sub(r'(?i)(apple)', r'(\1)', s)
for s in variants:
print(s, '-->', replace_apple_insensitive(s))
# I have apple. --> I have (apple).
# I have Apple. --> I have (Apple).
# I have APPLE and aPpLe. --> I have (APPLE) and (aPpLe).
或者你可以編譯正則表達式,並保持不區分大小寫的標誌出的格局:
apple_regex = re.compile(r'(apple)', flags=re.IGNORECASE) # or re.I
print(apple_regex.sub(r'(\1)', variants[2]))
#I have (APPLE) and (aPpLe).
見'IGNORECASE'標誌。 https://docs.python.org/2/howto/regex.html#compilation-flags –