如何用匹配的大小写替换正则表达式?

2024-06-26 14:41:57 发布

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

在使用正则表达式替换单词时,是否有一种优雅的方式来表示我希望替换的单词与被替换单词的第一个字母的大小写匹配?你知道吗

foo -> bar
Foo -> Bar
foO -> bar

一个不区分大小写的replace示例,但它不能正确地将Foo替换为Bar(而是bar)。你知道吗

re.sub(r'\bfoo\b', 'bar', 'this is Foo', flags=re.I)
# 'this is bar'

Tags: re示例foois字母方式barthis
2条回答

简而言之:没有

长话短说:

您可以使用finditer访问所有匹配项,然后手动执行大小写匹配。你知道吗

tests = (
        "11foo11",
        "22Foo22",
        "33foO33",
        "44FOO44",
)

import re
foobar = "(?i)(foo)"

for teststr in tests:
    replstr = "bar"

    newchars = list(teststr)

    for m in re.finditer(foobar, teststr):
        mtext = m.group(1)
        replchars = list(replstr)

        for i, ch in enumerate(mtext):
            if ch.isupper():
                replchars[i] = replchars[i].upper()

        newchars[m.start():m.end()] = replchars
        print("Old: ", teststr, " New: ", ''.join(newchars))

盒子里什么都没有。您需要使用replace函数。你知道吗

import re

def cased_replacer(s):
    def replacer(m):
        if m.group(0)[0].isupper():
            return s.capitalize()
        else:
            return s
    return replacer

re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is foo', flags=re.I)
# => 'this is bar'
re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is Foo', flags=re.I)
# => 'this is Bar'

相关问题 更多 >