我將我的bash代碼轉換爲python代碼。如何通過python的re模塊刪除最短匹配模式?
現在我想在bash中創建一個具有$ {variable#pattern}相同功能 的函數;該刪除最短匹配的模式,
例如,我期望delete_head( '_ usr_home_you_file.ext.tar.oz',R '_ * _')會導致 'home_you_file.ext.tar.oz'
我在下面製作了python函數,
import re
def delete_head(word,pattern):
re.sub('^{0}'.format(pattern), '', word)
但是,它會刪除最長的匹配模式,如下所示。
word='_usr_home_you_file.ext.tar.oz'
delete_shortest_match=delete_head(word,r'_.*_')
print("word = {0}".format(word))
print("delete_shortest_match = {0}". format(delete_shortest_match))
輸出:
word = _usr_home_you_file.ext.tar.oz
delete_shortest_match = file.ext.tar.oz # I expected home_you_file.ext.tar.oz
我怎樣才能讓像我上面預料它刪除最短的匹配模式的功能?
非常感謝。