Get the full substring matching the regex pattern
Question: I am not good with regular expressions and was looking at some online
resources for what I would like to do. So basically, I have a regular
expression in Python as follows:

    
    
    import re
    pattern = re.compile(r'(?=(ATG(?:...)*?)(?=TAG|TGA|TAA))')
    

This is supposed to find all sub strings which begin with ATG and end in TAG
or TGA or TAA. I use it as:

    
    
    str = "ATGCCCTAG"
    print pattern.findall(str)
    

However, this returns `ATGCCC` and removes the trailing `TAG` and I would like
it to keep the trailing `TAG`. How can I change it to give me the full
substring?


Answer: > To find all sub strings which begin with ATG and end in TAG or TGA or TAA

You will need a

    
    
    ATG(?:...)*?(?:TAG|TGA|TAA)
    

This regex also makes sure there are 0 or more 3-symbol (excl. newline)
sequences in-between `ATG` and the last `TAG`, `TGA` or `TAA`.

See [regex demo](https://regex101.com/r/xA8fU7/2)

[Python demo](https://ideone.com/TLsbiF):

    
    
    import re
    p = re.compile(r'ATG(?:...)*?(?:TAG|TGA|TAA)')
    test_str = "FFG FFG ATGCCCTAG"
    print (p.findall(test_str))
    

This will work if you need to find _non-overlapping_ substrings. To find
overlapping ones, the technique is to encapsulate that into a capturing group
and place in a non-anchored positive look-ahead:

    
    
    r'(?=(ATG(?:...)*?(?:TAG|TGA|TAA)))'
      |  |                           ||
      |  | --- Capture group ------- ||   
      | -- Positive look-ahead ------ |
    

See [regex demo](https://regex101.com/r/nQ7iH0/1)

