Reputation: 2226
I have a regex that matches an "aliases" key that is an existing list in a markdown file, and captures the closing bracket as a group.
RE_ALIASES = re.compile(r'\s*---\n.*aliases:\s?\[.*(\]|\n\]).*\n---.*', re.DOTALL)
How do I replace that captured group with my own text?
i.e.,
---
...
aliases: [
hello,
world
]
---
...
should be
---
...
aliases: [
hello,
world,
inserted
]
---
...
In this case, the first group \n]
is replaced by ,\n inserted\n]
Upvotes: 0
Views: 70
Reputation: 373
I think you should use the re.sub function
Here's how it would work for your case:
(Supposing you saved your initial string as initial_string)
final_string = re.sub('(\\]|\\n\\]).*', ',\n\tinserted\n\t]', initial_string)
If you print "final_string" it shows:
---
...
aliases: [
hello,
world,
inserted
]
---
...
Upvotes: 1