Python regex alpha-numeric string with numeric part between two values
<p>I am terrible at regex in general, but I would be interested to know if there is a method to check if the numeric part of an alpha-numeric string is between two values, or less/greater than a certain value?</p>

<p>For example if I have a string to search in a file which has multiple numeric variations like below:</p>

<pre><code>key_string (870 bytes)
key_string (1500 bytes)
key_string (70 bytes)
</code></pre>

<p>Is it possible to extract the 'key_string' string only on whether the '(xxxx bytes)' part is between a certain threshold, or less/greater than a certain value?</p>

<p>For example if I want to find all the above 'key_string' example where the second part is below 1200 bytes, can I print out:</p>

<pre><code>key_string (870 bytes)
key_string (70 bytes)
</code></pre>

<p>and ignore the string below in one regular expression? :</p>

<pre><code>key_string (1500 bytes)
</code></pre>

<p>You can use re.findall() to search along with regex.</p>

<p><strong>Explanation of regex as below:</strong></p>

<pre><code>key_string\s+\((\d+)\s+bytes\)
</code></pre>

<p><img src="https://www.debuggex.com/i/H8MpT5EfCmy2_MaX.png" alt="Regular expression visualization"></p>

<p><a href="https://www.debuggex.com/r/H8MpT5EfCmy2_MaX" rel="nofollow">Debuggex Demo</a></p>

<p><strong>Code:</strong></p>

<pre><code>import re

with open('result.txt') as fh:
    for l in fh:
        a = re.findall(r"key_string\s+\((\d+)\s+bytes\)",l.strip())
        if len(a) &gt; 0 and int(a[0]) &lt; 1200:
            print (l)
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py
key_string (870 bytes)

key_string (70 bytes)

C:\Users\dinesh_pundkar\Desktop&gt;
</code></pre>

<p><strong>Code 2 as suggested by <em>@WiktorStribiÅ¼ew</em> :</strong></p>

<pre><code>import re

pattern = r'key_string\s+\((\d+)\s+bytes\)'
regex = re.compile(pattern, re.IGNORECASE)
with open('result.txt') as fh:
    for match in regex.finditer(fh.read()):
        if int(match.group(1)) &lt; 1200:
            print((match.group()))
</code></pre>

python regex