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