std::正则表达式等同于'/g'全局修饰符
std::regex equivalent of '/g' global modifier
在Perl中,我可以做到这一点:
$text = '1747239';
@matches = ($text =~ m/(d)/g);
# @matches now contains ('1', '7', '4', '7', '2', '3', '9')
使用C++正则表达式匹配,复制这种行为的最佳方式是什么我得到一套包括所有比赛的比赛?
我现在有这个:-
compiledRegex = std::regex(regex, std::tr1::regex_constants::extended);
regex_search(text, results, compiledRegex);
int count = results.size();
// Alloc pointer array based on count * sizeof(mystruct).
for ( std::cmatch::iterator match = results.begin();
match != results.end();
++match )
{
// Do something with match;
}
然而,这只会给我第一个匹配,就像没有/g的Perl一样,这很好,但我喜欢/g效果。
那么,有没有一个好的方法可以做到这一点,或者我必须一遍又一遍地运行regex?
您应该多次调用regex_search
。其返回值指定是否有更多匹配项。每次你叫它,你就会得到一个新的匹配。结果返回的迭代器遍历正则表达式中定义的组子匹配。第一个条目总是完全匹配,这就是为什么在您的案例中count == 1
std::string::const_iterator text_iter = text.cbegin();
compiledRegex = std::regex(regex, std::tr1::regex_constants::extended);
while (regex_search(text_iter, text.end(), results, compiledRegex))
{
int count = results.size();
// Alloc pointer array based on count * sizeof(mystruct).
for ( std::cmatch::iterator group = results.begin();
group != results.end();
++group )
{
// If you uses grouping in your search here you can access each group
}
std::cout << std::string(results[0].first, results[0].second) << endl;
text_iter = results[0].second;
}
希望它能帮助
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- C++:匹配正则表达式,什么是匹配?
- std::正则表达式等同于'/g'全局修饰符