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')
CodePudding user response:
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 matchesMission = {
, then any zero or more chars as few as chars, and then} --End Mission
- Then
false
is replaced withfalse, \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))
CodePudding user response:
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
CodePudding user response:
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