C++ 正则表达式子匹配未出现

标签 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));

替换工作完美,这告诉我正则表达式是正确的。但是,不显示子匹配项。为什么子匹配不显示?

最佳答案

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

关于C++ 正则表达式子匹配未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30901329/

相关文章:

Javascript 链接自动嵌入与正则表达式

php - preg_match php 匹配 javascript

python - 使用Python正则表达式搜索包含字符的句子

C++: "Watch" "new", "delete"运算符的用法

c++ - 当我为调试 Lua 编译我的程序时运行良好,但为什么我为发布编译它我得到一个 c0000005 错误

c++ - 如何在我的 DLL 中调用我的 exe 中定义的函数?

java - 使用子字符串的数组中元素的索引

python - CMake 3.5中的链接器标志位置

c++ - 在对象是静态的类函数中声明静态变量是否有意义

javascript - 如何使用 javascript 正则表达式来验证城市名称?