2012-09-03 34 views
0

(可選)正則表達式所以我必須找到代碼中的函數的所有調用,如:_t(任何)也可以有參數給這些調用,如:「_t(anything,_t (anything2))「,對於這樣的例子,我只想匹配_t()的頂級調用,有沒有什麼辦法可以做到這一點?正則表達式匹配模式與(可選)

+0

什麼語言?這很容易(如果我正確理解問題),但某些語言可能沒有實現這個正則表達式的功能。 –

+0

我不喜歡使用PHP來做這件事的js文件中的這樣的字符串。 – lukasz

回答

0

我不確定是否只想匹配函數名稱或刪除參數(包括非頂級調用)。不管怎麼說here是取代正則表達式,輸出:

_t() 
_t() 
_t() 

_t(anything, _t(anything2)) 
_t(anything) 
_t(anything1, anything2) 

輸入:

/(_t\().*(\))/\1\2/g 
+0

我不想替換任何東西,只是想用_t()給出的所有參數找到所有的_t(),並且_t自己調用。 你的解決方案不適用於foo(_t()) – lukasz

+1

在澄清之後,我必須說'正則表達式'不是處理嵌套和遞歸結構的正確工具。這是因爲當從一個狀態轉移到另一個狀態時,狀態機不能存儲/調用數據(在這種情況下爲圓括號深度)。所以'正則表達式'不適合你的工作:) – fardjad

1

編程是關於選擇正確的工具的工作,和正則表達式是不真的是隻匹配函數頂層部分的正確工具。然而,編寫一個程序來抓取頂層部分是一件相當簡單的任務,這是一個用C++編寫的程序,可以實現這一點。它將解析存儲在變量「STR」的字符串,並找到存儲在「FUNC」的函數的頂部水平部分,所以在這種情況下,它找到「_T(」

#include <iostream> 
#include <string> 

using namespace std; 

int main() { 
    string str = "_t(another, anything)\nanything0 _t(anything, _t(anything2))\n_t(anything)\n_m(this, should, not, match)\n_t(anything1, anything2)"; 
    string func = "_t("; 

    int pos = 0; 
    int lastPos = 0; 

    while (pos != -1) { 
     pos = str.find (func, lastPos); 

     if (pos == -1) break; 

     int depth = 1; 
     string tmp; 

     pos += func.size(); 
     while (depth > 0) { 
     if (str[pos] == '(') { 
      depth++; 
     } 
     else if (str[pos] == ')') { 
      depth--; 
     } 

     if (depth != 0) { 
      tmp += str[pos]; 
     } 
     pos++; 
     } 

     cout << tmp << endl; 

     lastPos = pos; 
    } 

    return 0; 
} 

鑑於下列輸入(存儲在字符串中 「STR」):

_t(another, anything) 
anything0 _t(anything, _t(anything2)) 
_t(anything) 
_m(this, should, not, match) 
_t(anything1, anything2) 

以下是輸出:

another, anything 
anything, _t(anything2) 
anything 
anything1, anything2 


更新: 我確實覺得,與嵌套項目打交道時,正則表達式是不是真的是最好的解決方案,但是,這可能會爲你所需要的工作:

_t\(([\w\d _\(\),]+)?\) 

下面是一個例子,在PHP(因爲你說你在另一種意見是使用):

<?php 
$pattern = '/_t\(([\w\d _\(\),]+)?\)/'; 
$subject = '_t(another, anything)\nanything0 _t(anything, _t(anything2))\n_t(anything)\n_m(this, should, not, match)\n_t(anything1, anything2)'; 

preg_match_all ($pattern, $subject, $matches); 

print_r ($matches); 
?> 

從這個輸出如下:

Array 
(
    [0] => Array 
     (
      [0] => _t(another, anything) 
      [1] => _t(anything, _t(anything2)) 
      [2] => _t(anything) 
      [3] => _t(anything1, anything2) 
     ) 

    [1] => Array 
     (
      [0] => another, anything 
      [1] => anything, _t(anything2) 
      [2] => anything 
      [3] => anything1, anything2 
     ) 

) 

這似乎與您要查找的內容,在$匹配[1]陣列。

+0

我在想這樣的解決方案,但我認爲有一個更簡單的方法來使用正則表達式作爲「他們可以找到任何你想要的」:D thx給出一個想法,如果真的沒有辦法使用正則表達式生病吧,就這樣做。 – lukasz

+0

我正在玩這個的一些正則表達式,如果你想使用正則表達式,這可能適用於你所需要的:'_t \(([\ w \ d _ \(\),] +)?\) '。查看更新的帖子以獲取更多詳細信 – Alex