0

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]

1
  • Use re.sub Commented Mar 28, 2019 at 7:20

1 Answer 1

1

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
        ]
---
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.