如何用python中的case insentive string替换,目标字符串在?

时间:2017-04-15 09:54:45

标签: python regex string case-insensitive

我知道如何在python中替换字符串,但我只想在目标字符串周围添加一些标记,而目标字符串是caseinsentive。有什么简单的方法可以使用吗? 例如,我想在一些单词周围添加括号:

"I have apple."  ->  "I have (apple)."
"I have Apple."  ->  "I have (Apple)."
"I have APPLE."  ->  "I have (APPLE)."

1 个答案:

答案 0 :(得分:2)

您必须使匹配不区分大小写。 您可以在模式中包含标志,如:

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).