Regex matching for optional characters including question mark : <p>My string looks like this: "<a href="https://google.com/bar/foobar?count=1" rel="nofollow noreferrer">https://google.com/bar/foobar?count=1</a>" or it could be "<a href="https://google.com/bar/foobar" rel="nofollow noreferrer">https://google.com/bar/foobar</a>"</p>

<p>I want to extract the value <code>foobar</code> - it appears after <code>/bar</code> and has an optional <code>?</code></p>

<p>My regex looks like  this:
<code>m = re.match(r'(.*)/bar/(.*)((\?)(.*))?', data)</code></p>

<p>When I use this regex over example 2: <code>"https://google.com/bar/foobar"</code> I get two groups
<code>('https://google.com', 'foobar', None, None, None)</code></p>

<p>When I use this regex on the first example: <code>"https://google.com/bar/foobar?count=1"</code> I get</p>

<p><code>('https://google.com', 'foobar?count=3', None, None, None)</code></p>

<p>But I would like the second group to just be <code>foobar</code> without the <code>?count=3</code>
How would I achieve that?</p>

<p>My understanding so far is</p>

<p><code>(.*)/bar/(.*)((\?)(.*))?</code> is as follows:
<code>(.*)</code> matches the first part of the string. <code>\?</code> matches the <code>?</code> and <code>((\?)(.*))</code> matches <code>?count=3</code> and this is enclosed in <code>?</code> because it is supposed to be optional.</p>
