2017-08-17 64 views
0

我將我的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 

我怎樣才能讓像我上面預料它刪除最短的匹配模式的功能?

非常感謝。

回答

1

bash前綴不是正則表達式,而是遵循全局模式匹配規則。正則表達式中最短的匹配可以用懶惰來achived(正則表達式是由默認的貪婪)

r'_.*?_' 

,或者如果不支持或避免回溯

r'_[^_]*_' 
1

爲了獲得最短的匹配,加?非貪婪的限定符到*匹配零或更多量詞:_.*?_