import re

def extractreplacements(grammar):
    return [ (matchobj.group('pat'), matchobj.group('repl'), bool(matchobj.group('term')))
                for matchobj in re.finditer(syntaxre, grammar)
                if matchobj.group('rule')]

def replace(text, replacements):
    while True:
        for pat, repl, term in replacements:
            if pat in text:
                text = text.replace(pat, repl, 1)
                if term:
                    return text
                break
        else:
            return text

syntaxre = r

grammar1 = 

grammar2 = '''\

A -> apple
B -> bag
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''

grammar3 = '''\

A -> apple
WWWW -> with
Bgage -> ->.*
B -> bag
->.* -> money
W -> WW
S -> .shop
T -> the
the shop -> my brother
a never used -> .terminating rule
'''

grammar4 = '''\



_+1 -> _1+
1+1 -> 11+


1! ->!1
,! ->!+
_! -> _

1*1 -> x,@y
1x -> xX
X, -> 1,1
X1 -> 1X
_x -> _X
,x -> ,X
y1 -> 1y
y_ -> _

1@1 -> x,@y
1@_ -> @_
,@_ ->!_
++ -> +

_1 -> 1
1+_ -> 1
_+_ -> 
'''

grammar5 = '''\



A0 -> 1B

0A1 -> C01
1A1 -> C11

0B0 -> A01
1B0 -> A11

B1 -> 1B

0C0 -> B01
1C0 -> B11

0C1 -> H01
1C1 -> H11
'''

text1 = 

text2 = 

text3 = '_1111*11111_'

text4 = '000000A000000'


if __name__ == '__main__':
    assert replace(text1, extractreplacements(grammar1)) \
           == 'I bought a bag of apples from my brother.'
    assert replace(text1, extractreplacements(grammar2)) \
           == 'I bought a bag of apples from T shop.'
    
    assert replace(text2, extractreplacements(grammar3)) \
           == 'I bought a bag of apples with my money from T shop.'
    assert replace(text3, extractreplacements(grammar4)) \
           == '11111111111111111111'
    assert replace(text4, extractreplacements(grammar5)) \
           == '00011H1111000'