C++ 未显示正则表达式子匹配项

C++ Regex Sub Matches not appearing

本文关键字:正则表达式 显示 C++      更新时间:2023-10-16

我正在制作一个正则表达式来修改函数中的第二个和第三个参数。我正在使用大多数 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));

替换工作得很好,这告诉我正则表达式是正确的。但是,不会显示子匹配项。为什么子比赛不显示?

我认为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