我想基于类似于下面的逻辑将某些标志传递给re.compile函数。我想知道是否可以这样做。
flags = ""
if multiline:
flags = 're.M'
if dotall:
flags = flags + '|re.S'
if verbose:
flags = flags + '|re.X'
if ignorecase:
flags = flags + '|re.I'
if uni_code:
flags = flags + '|re.U'
regex = re.compile(r'Test Pattern', flags)
答案 0 :(得分:20)
re
标志只是数字。所以,我们需要二进制OR,就像这样
flags = 0
if multiline:
flags = re.M
if dotall:
flags |= re.S
if verbose:
flags |= re.X
if ignorecase:
flags |= re.I
if uni_code:
flags |= re.U
regex = re.compile(r'Test Pattern', flags)