Parseltongue
Parseltongue

Reputation: 11657

Match entire line containing certain text, and add a string after newline

Let's say I have a string like so:

*question: What percentage is the correct answer? 
    33%
    15%
    2%
    25%

I need to add, after the question line, a shuffle command:

*question: What percentage is the correct answer? 
    *shuffle
    33%
    15%
    2%
    25%

What is the best way for going about doing so? I'm fine using any Notepad editor or Python.

I thought I could use the following regex to capture everything on the first line: ^(\*question).*, but I'm not sure how to add the *shuffle syntax directly after the newline.

Upvotes: 2

Views: 39

Answers (2)

Code Maniac
Code Maniac

Reputation: 37755

You can use

^(\*question.*)

enter image description here

and replace by

\1\n\t*shffule

Regex demo

Upvotes: 2

Jan
Jan

Reputation: 43169

You may use

import re

data = """
*question: What percentage is the correct answer? 
    33%
    15%
    2%
    25%
"""

rx = re.compile(r'(\*question.+)', re.M)

data = rx.sub(r'\1\n    *shuffle', data)
print(data)

Which yields

*question: What percentage is the correct answer? 
    *shuffle
    33%
    15%
    2%
    25%

Upvotes: 2

Related Questions