Python ProgrammingPython Programming

Python Find pattern in a string

import re

s1 = 'abccba'
s2 = 'abcabc'
s3 = 'canadajapanuaeuaejapancanada'
p = '123321'


def match(s, p):
    nr = {}
    regex = []
    for c in p:
        if c not in nr:
            regex.append('(.+)')
            nr[c] = len(nr) + 1
        else:
            regex.append('\\%d' % nr[c])
    return bool(re.match(''.join(regex) + '$', s))


print(match(s1, p))
print(match(s2, p))
print(match(s3, p))
Output
True
False
True