I am in need of regex which can capture till specified number of full stopd after a particular word.

Consider this text:

Stack Overflow

It is great website. It works very well.Lot of people help each other.

I love it.

I want my regex to stop capturing after it has encountered 2/3/4 (according to my need in different scenarios) full stops after the Stack Overflow word.

My Regex captures as many as it can get:

p = r'((\bStack Overflow\b)\s*.*(?=\.))'
lst = re.findall(p, text, re.I|re.M|re.DOTALL)

If I make it non-greedy and use a regex like below. It stops at 1st full stop.

p = r'((\bStack Overflow\b)\s*.*?(?=\.))'

I know I have to use {2} somewhere but can't figure out.

1 Answers

CertainPerformance On Best Solutions

Repeat a group that matches non-period characters, followed by a period character. The number of times you repeat that group will be the number of periods after Stack Overflow that get matched. For example:

\bStack Overflow\b(?:[^\.]*\.){2}

will match 2 sentences (or just periods) after Overflow.