Just don't automatically call .group(2)
for B and C. This assumes that you know you'll always find a match for A.
def function(input):
data = input.txt
A = re.search(r'(re)(ge)(x1)',data).group(2)
gb = re.search(r'(re)(ge)(x2)',data)
B = gb.group(2) if gb else ""
gc = re.search(r'(re)(ge)(x3)',data)
C = gc.group(2) if gc else ""
return "%stext%s%s" % (A, B, C)