Elegant way to replace substring in a regex with optional groups in Python?
import re

regex = re.compile(
    r'(The|A) '
    r'\w+'
    r'( is )'
    r'\w+'
    r'(?:'
        r'( and I )'
        r'\w+'
        r'( it)'
    r')?'
)


def repl(sentence, subject, colour, verb=None):
    m = regex.match(sentence)
    new = m.expand(rf'\1 {subject}\2{colour}')
    if m[3]:
        new += m.expand(rf'\3{verb}\4')
    return new


def test():
    assert repl('The sky is blue and I like it', 'bathroom', 'smelly', 'distrust') == \
        'The bathroom is smelly and I distrust it'
    assert repl('The tree is green and I love it', 'pinata', 'angry', 'fear') == \
        'The pinata is angry and I fear it'
    assert repl('A lemon is yellow', 'population', 'dumbfounded') == \
        'A population is dumbfounded'


Essentially, invert the sections of the regex around which you put groups; they're the things you want to save.