如何编写一个regex来替换一个单词,但在Python中保持大小写?

2024-09-30 00:23:04 发布

您现在位置:Python中文网/ 问答频道 /正文

这有可能吗?在

基本上,我想将这两个调用转换为一个单独的调用:

re.sub(r'\bAword\b', 'Bword', mystring)
re.sub(r'\baword\b', 'bword', mystring)

我真正想要的是某种条件替换符号,比如:

^{pr2}$

我只关心第一个字符的大写。其他人都没有。在


Tags: re符号条件字符大写关心mystringpr2
3条回答

您可以使用函数来分析每个匹配项:

>>> def f(match):
        return chr(ord(match.group(0)[0]) + 1) + match.group(0)[1:]

>>> re.sub(r'\b[aA]word\b', f, 'aword Aword')
'bword Bword'

可以传递使用Match对象作为参数的lambda函数作为替换函数:

import re
re.sub(r'\baword\b', 
       lambda m: m.group(0)[0].lower() == m.group(0)[0] and 'bword' or 'Bword',
       'Aword aword', 
       flags=re.I)
# returns: 'Bword bword'

好的,这是我想出的解决方案,多亏了使用replace函数的建议。在

re.sub(r'\b[Aa]word\b', lambda x: ('B' if x.group()[0].isupper() else 'b') + 'word', 'Aword  aword.')

相关问题 更多 >

    热门问题