Match RegEx pattern within pattern

Folks,

I have to match the following pattern:

First letter must be N Second any letter except P Third have to be S or T and the Fourth any letter except P again.

The string is only capital letters, no number, white spaces, etc.

So using python this is what I got so far:

import re
strRegex = r"N[^P][ST][^P]"
objRegex = re.compile(strRegex)

print objRegex.findall('NNSTL')

This will print: NNST

What I expect is: NNST and NSTL

Thanks

Upvotes: 2

Views: 1065

Answers (1)

sanooj
sanooj

Reputation: 493

re.findall will only return non-overlapping matches

Try this:

    >>> strRegex = r"N[^P][ST][^P]"
    >>> regex = compile(strRegex)
    >>> def newfind(regex,str,pos=0):
    ...    result=regex.search(str,pos)
    ...    if result is None: return []
    ...    else: return [result.group()]+newfind(regex,str,result.start()+1)
    ...
    >>>
    >>> newfind(regex,'NNSTL')
    ['NNST', 'NSTL']

Reference: https://mail.python.org/pipermail/tutor/2005-September/041126.html

Upvotes: 1

Related Questions