2015-06-17 35 views
1

我正在制定一個正則表達式來修改函數中的第二個和第三個參數。我正在使用大多數Linux發行版附帶的regex.h庫。我似乎無法讓submatches出現在下面的代碼中。C++正則表達式子匹配不出現

代碼:

 string s ("tweenArray.push(addNewPoint(posTween, 1 , 2, .3, scale, brushWidth));"); 
     regex e ("(tweenArray.push\\(addNewPoint\\(posTween,)\s*(.+?),\s*(.+?),"); // matches words beginning by "sub" 
     smatch m; 

     regex_match (s, m, e); 
     cout << "match " << 0 << " (" << m[0] << ")" << endl; 
     cout << "match " << 1 << " (" << m[1] << ")" << endl; 
     cout << "match " << 2 << " (" << m[2] << ")" << endl; 
     cout << "match " << 3 << " (" << m[3] << ")" << endl; 
     cout << regex_replace (s,e,"$1 0, 0"); 

輸出:

 match 0() 
     match 1() 
     match 2() 
     match 3() 
     tweenArray.push(addNewPoint(posTween, 0 , 0, .3 scale, brushWidth)); 

替換的作品完美,它告訴我,正則表達式正確。但是,子匹配沒有被顯示。爲什麼不會顯示子匹配?

+1

你匹配組的匹配'addNewPoint'只匹配前兩個參數參數。你可以嘗試這個正則表達式'(tweenArray \\。push \\(addNewPoint \\(posTween,)\\ s *?((。+?\ s *?),)+ \\ s *?(。+? )+ \\)\\);' – Signus

+0

對不起,我應該更具體一些,我只想捕獲addNewPoint函數的第二個和第三個參數。所以我想引用「1」和「2」。 – shockawave123

回答

2

我認爲regex_match需要整個字符串匹配。

Important 
Note that the result is true only if the expression matches the whole of 
the input sequence. If you want to search for an expression somewhere 
within the sequence then use regex_search. If you want to match a prefix of 
the character string then use regex_search with the flag match_continuous set. 

所以,也許這將工作

".*?tweenArray.push\\(addNewPoint\\(posTween,\\s*(.+?),\\s*(.+?),.*"

.*? 
tweenArray . push\(addNewPoint\(posTween, 
\s* 
(.+?)      # (1) 
, \s* 
(.+?)      # (2) 
, 
.* 

輸出:

** Grp 0 - (pos 0 , len 69) 
tweenArray.push(addNewPoint(posTween, 1 , 2, .3, scale, brushWidth)); 
** Grp 1 - (pos 38 , len 2) 
1 
** Grp 2 - (pos 42 , len 1) 
2 
+0

謝謝,這工作完美!非常感謝您的幫助。 – shockawave123