: は例えば、私は次のようにいくつかの単語を中心にブラケットを追加します。 あなたがのように、パターンにフラグを含めることができます。
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 –