Python 3 regex word boundary unclear
<p>I am using a regex to find the string 'my car' and detect up to four words before it. My reference text is:</p>

<pre><code>my house is painted white, my car is red.
A horse is galloping very fast in the road, I drive my car slowly.
</code></pre>

<p>if I use the regex:</p>

<pre><code>re.finditer(r'(?:\w+[ \t,]+){0,4}my car',txt,re.IGNORECASE|re.MULTILINE)
</code></pre>

<p>I am getting the expected results.For example: house is painted white, my car</p>

<p>if I use the regex:</p>

<pre><code>re.finditer(r'(?:\w+\b){0,4}my car',txt,re.IGNORECASE|re.MULTILINE)
</code></pre>

<p>I am getting only: 'my car' and 'my car'
That is, I am not getting up to four words before it.
Why I cannot use the \b to match the words in the group {0,4}?</p>

<p>Because <code>\b</code> is a <em>zero-width assertion</em> <a href="http://www.regular-expressions.info/wordboundaries.html" rel="nofollow"><strong>word boundary</strong></a> matching a <em>location</em> between the start of string and a word char, between a non-word char and a word char, between a word char and a non-word char and between a word char and end of string. <strong>It does not <em>consume</em> the text</strong>.</p>

<p>The <code>(?:\w+\b){0,4}</code> just matches an empty string since there is no 1+ word chasrs followed with a word boundary before <code>my car</code>. </p>

<p>Instead, you may want to match 1+ non-word chars that will effectively imitate a word boundary:</p>

<pre><code>(?:\w+\W+){0,4}my car\b
</code></pre>

<p>See the <a href="https://regex101.com/r/kP5nD4/2" rel="nofollow">regex demo</a></p>

python regex python-3.x