我需要re模塊的幫助。我有模式:Python:正則表達式:查找是否存在,否則忽略
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來做,但我需要跨平臺的方式來做到這一點。有可能嗎? Tnanks!
P.S.這也將是巨大的,如果字符串的順序將是免費的,不是固定不變的:
text = '''other(other)
first_condition(enabled)'''
必須返回絕對是一樣的:
[('enabled', '', '', 'something')]
你真的想要得到的結果是包含一個元組的列表? –
@MarkByers:不,單個列表甚至更好。 – ghostmansd
或單個元組,不需要。 – ghostmansd