'How can I use a regex expression to identify the falses between braces on different lines?

I'm attempting to use the Python re.sub module to replace any instance of false in the example below with "false, \n"

local Mission = {

    start_done = false
    game_over = false

} --End Mission

I've attempted the following, but I'm not getting a successful replacements. The idea being I start and end with the anchor strings, skip over anything that isn't a "false", and return "false + ','" when I get a match. Any help would be appreciated!

re.sub(r'(Mission = {)(.+?)(false)(.+?)(} --End Mission)', r'\1' + ',' + '\n')


Solution 1:[1]

You can use

re.sub(r'Mission = {.*?} --End Mission', lambda x: x.group().replace('false', 'false, \n'), text, flags=re.S)

See the regex demo.

Notes:

  • The Mission = {.*?} --End Mission regex matches Mission = {, then any zero or more chars as few as chars, and then } --End Mission
  • Then false is replaced with false, \n in the matched texts.

See the Python demo:

import re
text = 'local Mission = {\n    start_done = false\n    game_over = false\n\n} --End Mission'
rx = r'Mission = {.*?} --End Mission'
print(re.sub(rx, lambda x: x.group().replace('false', 'false, \n'), text, flags=re.S))

Solution 2:[2]

Another option without regex:

your_string = 'local Mission = {\n    start_done = false\n    game_over = false\n\n} --End Mission'
print(your_string.replace(' = false\n', ' = false,\n'))

Output:

local Mission = {
    start_done = false,
    game_over = false,

} --End Mission

Solution 3:[3]

Provided that every "false" string which is preceded by = and followed by \n has to be substituted then here a regex:

re.sub(r'= (false)\n', r'= \1,\n', text)

Note: you introduce 5 groups in your regex so you should have used \3 and not \1 to refer to "false", group start from 1, see doc at paragraph \number

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Wiktor Stribiżew
Solution 2 lemon
Solution 3