C ++ Regex Sub Matches没有出现

时间:2015-06-17 20:03:38

标签: c++ regex

我正在制作一个正则表达式来修改函数中的第二个和第三个参数。我正在使用大多数Linux发行版附带的regex.h库。我似乎无法让子匹配出现在下面的代码中。

代码:

       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 个答案:

答案 0 :(得分: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