Loop through a finite language described by regex in python
<p>The given input is a regex that describe a finite language. Is there a simple way to enumerate the language in python (or in other programming language)?</p>

<p>The following is what I expect:</p>

<p>Psuedocode:</p>

<pre><code>for x in r'[a-c]':
    print(x)
</code></pre>

<p>Output:</p>

<pre><code>a
b
c
</code></pre>

<p>There's no way to do this with the built-in <code>re</code> module.</p>

<p>Instead, what you need to do is build your own regular expression parser and use that to generate your language.</p>

<p>Just to see if I could do it, I made a <em>basic</em> regular expression parser and generator.  The code is 410 lines long including some minimal documentation, so probably too big to fit here, so it's in a <a href="https://gist.github.com/jearls/a8235e13c21f2c2a283dd4080f3cee17" rel="nofollow">gist</a>.</p>

<p>Sample output:</p>

<pre><code>$ python regen.py '[a-c]'
'a'
'b'
'c'
</code></pre>

<p>Sequence of items:</p>

<pre><code>$ python regen.py '[a-c][1-5]'
'a1'
'a2'
'a3'
'a4'
'a5'
'b1'
'b2'
'b3'
'b4'
'b5'
'c1'
'c2'
'c3'
'c4'
'c5'
</code></pre>

<p>Alternate items:</p>

<pre><code>$ python regen.py '[a-c]|[1-5]'
'a'
'b'
'c'
'1'
'2'
'3'
'4'
'5'
</code></pre>

<p>Infinite operators are capped at 5 repetitions...</p>

<pre><code>$ python regen.py 'a*'
''
'a'
'aa'
'aaa'
'aaaa'
'aaaaa'
</code></pre>

<p>but finite operators are not:</p>

<pre><code>$ python regen.py 'a{3,6}'
'aaa'
'aaaa'
'aaaaa'
'aaaaaa'
</code></pre>

python regex