Regex taking too long in python
<p>I have used regex101 to test my regex and it works fine.What i am trying to is to detect these patterns</p>

<ol>
<li>section 1.2 random 2</li>
<li>1.2 random 2</li>
<li>1.2. random 2</li>
<li>random 2</li>
<li>random 2.</li>
</ol>

<p>But its just random it shouldn't match if the string is like that</p>

<ol>
<li>random</li>
</ol>

<p>My regex is this.</p>

<pre><code>  m = re.match(r"^(((section)\s*|(\d+\.)|\d+|(\d+\.\d+)|[a-zA-z\s]|[a-zA-z\.\s])+((\d+\.$)|\d+$|(\d+\.\d+$)))","random random random random random",flags = re.I)
</code></pre>

<p>If i give in a long string it gets stuck.Any ideas?</p>

<p>After some simplification, this regular expression meets the requirements stated above and reproduced in the test cases below.</p>

<pre><code>import re

regex = r'(?:section)*\s*(?:[0-9.])*\s*random\s+(?!random)(?:[0-9.])*'

strings = [
   "random random random random random",
   "section 1.2 random 2",
   "1.2 random 2",
   "1.2. random 2",
   "random 2",
   "random 2.",
   "random",
]

for string in strings:
    m = re.match(regex, string, flags = re.I)
    if m:
        print "match on", string
    else:
        print "non match on", string
</code></pre>

<p>which gives an output of:</p>

<pre><code>non match on random random random random random
match on section 1.2 random 2
match on 1.2 random 2
match on 1.2. random 2
match on random 2
match on random 2.
non match on random
</code></pre>

<p>See it in action at: <a href="https://eval.in/661183" rel="nofollow">https://eval.in/661183</a></p>

python regex