2011-06-22 40 views
0

我問this question earlier但我沒有正確表達自己。如果我有這三種情況:如何找到不在註釋中的方法名稱?

void aMethod(params ...) 
//void aMethod(params 
// void aMethod(params 
^can have any number of spaces here 

我怎麼能調整到符合我的正則表達式只有在字符串未在評論中發現?這是我的正則表達式:

re.search("(?<!\/\/)\s*void aMethod",buffer) 

這會捕獲一切:

(?<!\/\/)(?<!\s)+void onMouseReleased 
+4

這些是唯一的三種情況嗎?怎麼樣:'/ * foo void aMethod(params)bar * /'(多行註釋)和'「foo void aMethod(params)bar」'(字符串文字) –

+0

Python沒有標記器嗎? – KingCrunch

+0

@Bart,多行不會出現。 – Geo

回答

3

這應該爲你的例子做的東西:

re.search("^(?!\/\/)\s*void aMethod",line) 
+0

我只是好奇,會有一個負面的看後面的解決方案嗎? – Geo

+0

@Geo,不,因爲背後的外觀必須有固定的寬度。所以你不能把'\ s *'或'\ s +'放在一個後視中。 –

+0

是的,我知道固定寬度。但是不能用+來重複後視效果,就像後視太空一樣? – Geo

1

是否有使用正則表達式的任何特殊需求?如果沒有,你也可以嘗試使用以下命令:

a = """void aMethod(params ...) 
//void aMethod(params 
// void aMethod(params 
^can have any number of spaces here""" 

for line in a.split('\n'): 
    if not line.strip().startswith("//") and "void aMethod(params" in line: 
     print line 

市價修改lazyr評論

+2

這將排除'void aMethod(params //',它應該包含在內,並且包括'var =」asdf aMethod asdf「',這應該被排除。 ()「和」void aMethod(params「in line」)。請記住,這隻適用於沒有多餘空格的情況,像這樣:void aMethod(params'。 –

+0

@ lazyr,謝謝,編輯 –

相關問題