Tho*_*ini 4 c++ regex boost boost-regex
嘿,让我说我有这个正则表达式: (test[0-9])+
我将它与之匹配: test1test2test3test0
const bool ret = boost::regex_search(input, what, r);
for (size_t i = 0; i < what.size(); ++i)
cout << i << ':' << string(what[i]) << "\n";
Run Code Online (Sandbox Code Playgroud)
现在,what[1]将是test0(最后一次出现).让我们说我需要得到test1,2和3:我该怎么办?
注意:真正的正则表达式非常复杂,并且必须保持一个整体匹配,因此将示例正则表达式更改为(test[0-9])不起作用.
小智 10
我认为Dot Net能够制作单个捕获组集合,以便(grp)+将在group1上创建一个集合对象.boost引擎的regex_search()就像任何普通的匹配函数一样.你坐在while()循环中,匹配最后一个匹配的模式.您使用的表单不使用bid-itterator,因此该函数不会启动最后一个匹配停止的下一个匹配项.
您可以使用itterator形式:
(编辑 -你也可以使用该令牌迭代器,定义哪些群体遍历添加下面的代码).
#include <boost/regex.hpp>
#include <string>
#include <iostream>
using namespace std;
using namespace boost;
int main()
{
string input = "test1 ,, test2,, test3,, test0,,";
boost::regex r("(test[0-9])(?:$|[ ,]+)");
boost::smatch what;
std::string::const_iterator start = input.begin();
std::string::const_iterator end = input.end();
while (boost::regex_search(start, end, what, r))
{
string stest(what[1].first, what[1].second);
cout << stest << endl;
// Update the beginning of the range to the character
// following the whole match
start = what[0].second;
}
// Alternate method using token iterator
const int subs[] = {1}; // we just want to see group 1
boost::sregex_token_iterator i(input.begin(), input.end(), r, subs);
boost::sregex_token_iterator j;
while(i != j)
{
cout << *i++ << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
test1
test2
test3
test0
Boost.Regex为这个功能提供了实验支持(称为重复捕获); 但是,由于它的性能很高,默认情况下会禁用此功能.
要启用重复捕获,您需要重建Boost.Regex并BOOST_REGEX_MATCH_EXTRA在所有翻译单元中定义宏; 最好的方法是在boost/regex/user.hpp中取消注释这个定义(参见参考资料,它位于页面的最底部).
一旦这个定义编译的,你可以通过调用/使用使用此功能regex_search,regex_match并regex_iterator具有match_extra标志.
有关详细信息,请查看Boost.Regex的参考.
| 归档时间: |
|
| 查看次数: |
9822 次 |
| 最近记录: |