Extract sub path from url with regex
<p>I have this url:</p>

<pre><code> http://www.example.com/en/news/2016/07/17/1207151/%D9%81%D8%AA%D9%88%D8%A7%DB%8C-%D8%B1%D9%87%D8%A8%D8%B1-
</code></pre>

<p>I am going to extract <code>1207151</code> here.</p>

<p>here is my regext:</p>

<pre><code>pattern = '(http[s]?:\/\/)?([^\/\s]+\/)+[^/]+[^/]+[^/]+[^/]/(?&lt;field1&gt;[^/]+)/'
</code></pre>

<p>but it's wrong!</p>

<p>what is my mistake?</p>

<p>You've got a couple things going on.</p>

<p>First you'll need to properly escape all of your <code>/</code>s. You've got most of them, but missed a couple:</p>

<pre><code>(http[s]?:\/\/)?([^\/\s]+\/)+[^\/]+[^\/]+[^\/]+[^\/]\/(?&lt;field1&gt;[^\/]+)\/
</code></pre>

<p>From here, you have a number of "1 or more not /" in a row that can be reduced:</p>

<pre><code>[^\/]+[^\/]+[^\/]+ ==&gt; [^\/]{3,}
</code></pre>

<p>But that's not what you meant to do, you meant to have many blocks of "non /" followed by a "/" and based on your example, you want it 6 times before using your named capture group.</p>

<pre><code>([^\/]+\/){6}
</code></pre>

<p>Here's what works:</p>

<pre><code>http[s]?:\/\/([^\/]+\/){6}(?&lt;field1&gt;[^\/]+)\/
</code></pre>

<p>And you can see it in action here: <a href="https://regex101.com/r/kkqwRJ/2" rel="nofollow">https://regex101.com/r/kkqwRJ/2</a></p>

python regex url