How to use Boolean OR inside a regex
<p>I want to use a regex to find a substring, followed by a variable number of characters, followed by any of several substrings.</p>

<p>an re.findall of</p>

<pre><code>"ATGTCAGGTAAGCTTAGGGCTTTAGGATT"
</code></pre>

<p>should give me:</p>

<pre><code>['ATGTCAGGTAA', 'ATGTCAGGTAAGCTTAG', 'ATGTCAGGTAAGCTTAGGGCTTTAG']
</code></pre>

<p>I have tried all of the following without success:</p>

<pre><code>import re
string2 = "ATGTCAGGTAAGCTTAGGGCTTTAGGATT"
re.findall('(ATG.*TAA)|(ATG.*TAG)', string2)
re.findall('ATG.*(TAA|TAG)', string2)
re.findall('ATG.*((TAA)|(TAG))', string2)
re.findall('ATG.*(TAA)|(TAG)', string2)
re.findall('ATG.*(TAA)|ATG.*(TAG)', string2)
re.findall('(ATG.*)(TAA)|(ATG.*)(TAG)', string2)
re.findall('(ATG.*)TAA|(ATG.*)TAG', string2)
</code></pre>

<p>What am I missing here?</p>

<p>This is not super-easy, because a) you want overlapping matches, and b) you want greedy and non-greedy and everything inbetween.</p>

<p>As long as the strings are fairly short, you can check every substring:</p>

<pre><code>import re
s = "ATGTCAGGTAAGCTTAGGGCTTTAGGATT"
p = re.compile(r'ATG.*TA[GA]$')

for start in range(len(s)-6):  # string is at least 6 letters long
    for end in range(start+6, len(s)):
        if p.match(s, pos=start, endpos=end):
            print(s[start:end])
</code></pre>

<p>This prints:</p>

<pre><code>ATGTCAGGTAA
ATGTCAGGTAAGCTTAG
ATGTCAGGTAAGCTTAGGGCTTTAG
</code></pre>

<p>Since you appear to work with DNA sequences or something like that, make sure to check out <a href="http://biopython.org" rel="nofollow">Biopython</a>, too.</p>

python regex parsing boolean-logic