Mr_and_Mrs_D Mr_and_Mrs_D - 1 month ago 11
Python Question

Match two groups but none of them should be empty

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)


but this also matches empty filenames (with extension only). Can't wrap my head around similar questions like:



The extra complication is that the second group (the digits) may not be added

So valid:

abc%.exe
123.exe


If has_digits is true:

abc 123.exe # I want the second group to contain the 123 not the first one


Invalid :
.exe

Answer

Regex:

^(.*?)(\d+)?(?<=.)\.exe$

Positive lookbehind assures that there is at least one character before extension part.

Live demo

Integrated:

regex = '^(.*?)'
if has_digits: regex += '(\d+)?'
regex += '(?<=.)' + ext + '$'
rePattern = re.compile(regex, re.I | re.U)
Comments