I want my regex to be able to match strings of random chars optionally followed by some digits - but if both matches are empty I want the match to fail. I am currently constructing the regex as in:
regex = u'^(.*)'
if has_digits: regex += u'(\d*)'
regex += ext + u'$' # extension group as in u'(\.exe)'
rePattern = re.compile(regex, re.I | re.U)
abc 123.exe # I want the second group to contain the 123 not the first one
Positive lookbehind assures that there is at least one character before extension part.
regex = '^(.*?)' if has_digits: regex += '(\d+)?' regex += '(?<=.)' + ext + '$' rePattern = re.compile(regex, re.I | re.U)