Mr_and_Mrs_D Mr_and_Mrs_D - 1 year ago 63
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:


If has_digits is true:

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

Invalid :

Answer Source



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

Live demo


regex = '^(.*?)'
if has_digits: regex += '(\d+)?'
regex += '(?<=.)' + ext + '$'
rePattern = re.compile(regex, re.I | re.U)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download