我需要关于 re 模块的帮助。我有模式:
pattern = re.compile('''first_condition\((.*)\)
extra_condition\((.*)\)
testing\((.*)\)
other\((.*)\)''', re.UNICODE)
如果我对以下文本运行正则表达式,就会发生这种情况:
text = '''first_condition(enabled)
extra_condition(disabled)
testing(example)
other(something)'''
result = pattern.findall(text)
print(result)
[('enabled', 'disabled', 'example', 'something')]
但是如果遗漏了一两行,正则表达式会返回空列表。例如我的文字是:
text = '''first_condition(enabled)
other(other)'''
我想得到什么:
[('enabled', '', '', 'something')]
我可以在几个命令中执行此操作,但我认为它会比在一个正则表达式中执行此操作要慢。原始代码使用sed,所以速度非常快。我可以使用 sed 来做到这一点,但我需要跨平台的方式来做到这一点。有可能吗?坦克!
PS如果字符串序列是免费的,而不是固定的,那也很棒:
text = '''other(other)
first_condition(enabled)'''
必须返回完全相同:
[('enabled', '', '', 'something')]