How to replace regular expression with appropriate case?

When replacing words using regular expressions, is there an elegant way to indicate that I want the replacement to match the upper / lower case of the first letter of the replaced word?

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

The case insensitivity example replaces, but it will not correctly replace Foowith Bar(instead, it Bar).

re.sub(r'\bfoo\b', 'bar', 'this is Foo', flags=re.I)
# 'this is bar'
+4
source share
2 answers

Nothing out of the box. You need to use the replace function.

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'
+4
source

The short answer is no.

Long answer:

You can do this by using finditerto view all matches, and then manually match the examples.

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))
+2

Source: https://habr.com/ru/post/1627890/


All Articles