import regex as re
expressions = r'''CARS?|(AUTO|BIG)?TRUCK|VEHICLE|(CRUISE|CONTAINER)? SHIP|AUTOMOTIVE'''
# first alternative using (*SKIP)(*FAIL)
rx = re.compile(r'\([^()]*\)(*SKIP)(*FAIL)|\|')
parts = "\n".join(rx.split(expressions))
print(parts)
# second, a function
rx = re.compile(r'\([^()]*\)|(\|)')
def replacer(match):
if match.group(1):
return 'SUPERMAN'
else:
return match.group(0)
expressions = rx.sub(replacer, expressions)
parts = "\n".join(expressions.split('SUPERMAN'))
print(parts)
这里至少有两种可能性,一种是使用较新的
(*SKIP)(*FAIL)
机制,另一种是使用函数(首先替换所讨论的|
):两者都会屈服
相关问题 更多 >
编程相关推荐