2014-10-11 22 views
0

每當正則表達式匹配字符串myString時,我使用下面的代碼來調用replace函數。我的問題是我是否可以調用基於不同的替換功能的正則表達式是否與${STRING}匹配或$STRING調用替換函數正則表達式Python

def replace(match): 
    match = match.group() 

    if matched == ${STRING} 
     return os.getenv(match[1:],'') 
    elif matched == $STRING: 
     return something else 
    else: 
     return error 

def main() 
    myString = "my string ${withcool} $stuff" 
    re.sub("\$.+|\$\{.+\}",replace,myString) 
+1

您將需要一個函數或至少一個簡短的lambda表達式來決定調用哪個函數。 – grc 2014-10-11 04:33:18

回答

0

我想你想提取變量和評估。

如果是這樣,你不需要調用不同的函數來提取變量,你可以使用圓括號(捕獲組)來提取它。

像:

def replace(match): 
    print match.groups() 
s='my string ${withcool} ${withcool2} $stuff' 
re.sub(r'\$\{(\w+)\}', replace, s) 

它將給:

('withcool',) 
('withcool2',) 

正如你看到的,變量已經提取。

但是,如果你想匹配兩個或更多的模式,它會有點複雜。

如果使用re.sub(r'\$(\w+)|\$\{(\w+)\}', replace, s)match.groups()將是:

(None, 'withcool') 
(None, 'withcool2') 
('stuff', None) 

你需要得到它不是從數組None的元素。

順便說一句,我建議使用\w而不是.,因爲你正在使用貪婪的正則表達式。