r/regex•
arjun2502

How to repeat a sentence "n"number of times from a paragraph?

Hi, Is it possible to repeat a sentence 3 times.

Example: INPUT: This is regex subreddit. You can learn regex here. Have a good day.

Output: This is regex subreddit. This is regex subreddit. This is regex subreddit. You can learn regex here.You can learn regex here.You can learn regex here. Have a good day. Have a good day. Have a good day.

Thank you.

Posted Dec 28, 2020, 12:24 AM UTC

11
Kompaan86•

Unless you know how many sentences there are (or at least an upper bound) and it's within the limits of your regex implementation, I think you'll need some code.

Example with limited groups

Python code sample although there's probably much better ways of doing this:

import re

regex = r"""
	^([^.]+\.\s)
	"""

string = (
    "This is regex subreddit. You can learn regex here. Have a good day. "
    )

result = ""

while True:
    firstmatch = re.match(regex,string, re.VERBOSE | re.DOTALL)
    try:
        # truncate string
        string = string[firstmatch.end():]
        # add the match three times
        result = result + firstmatch.group() * 3
    except AttributeError:
        # no more groups
        break

print(result)
2
[deleted]•

[deleted]

1