递归匹配与 boost 正则表达式库
recursive match with boost regex library
我是新手,试图从下面的字符串中构造一个向量(它将是持有方向(Y/NO)和计数的对象向量),但这个字符串长度是任意的,有人可以建议如何将确切的字符串与boost::regex
匹配并存储它吗?
std::string str = "Y-10,NO-3,NO-4,Y-100"
编辑:这就是我所做的,但不确定这是否是最佳的?
boost::regex expr{"((Y|NO)-\d+)"};
boost::regex_token_iterator<std::string::iterator> it{pattern.begin(), pattern.end(), expr, 1};
boost::regex_token_iterator<std::string::iterator> end;
while (it != end) {
std::string pat = *it;
boost::regex sub_expr {"(Y|NO)-(\d+)"};
boost::smatch match;
if (boost::regex_search(pat, match, sub_expr)) {
...
...
}
}
我会在这里使用Spirit:
住在科里鲁
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
enum class YNO { NO, Y };
struct YNoToken : qi::symbols<char, YNO> {
YNoToken() { add("Y", YNO::Y)("NO", YNO::NO); }
} static YNo;
int main() {
std::string const str = "Y-10,NO-3,NO-4,Y-100";
auto f = str.begin(), l = str.end();
std::vector<std::pair<YNO, int> > v;
bool ok = qi::parse(f, l, (YNo >> '-' >> qi::int_) % ',', v);
if (ok) {
std::cout << "Parse success: n";
for (auto pair : v)
std::cout << (pair.first==YNO::Y? "Y":"NO") << "t" << pair.second << "n";
}
else
std::cout << "Parse failedn";
if (f!=l)
std::cout << "Remaining unparsed: '" << std::string(f,l) << "'n";
}
指纹
Parse success:
Y 10
NO 3
NO 4
Y 100
您可以使用正则表达式获得类似的结果,但您需要做手动工作来检查和转换子匹配项。
相关文章:
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 为什么 Boost:正则表达式没有按预期找到所有结果?
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用 boost::regex (c++) 比较两个正则表达式
- 我的 Boost 正则表达式与任何内容都不匹配
- 使用boost正则表达式时出现shared_ptr错误
- Boost正则表达式:链接时未定义的引用
- 如何使用perl样式内存正则表达式与Boost库匹配
- 如何获得与 C++11 或 Boost 匹配的正则表达式长度
- 递归匹配与 boost 正则表达式库
- 提高Boost正则表达式的速度或在C++中使用PCRE
- boost正则表达式中的命名捕获/组列表
- 使用Boost替换正则表达式
- 关于正则表达式与Boost的逻辑AND和OR匹配的说明
- 将 C++11 正则表达式与 gcc 4.8.2 一起使用时会出现奇怪的结果(但适用于 Boost 正则表达式)
- 使用 Boost 的 C++ 中的正则表达式
- Boost::qt Creator中的正则表达式
- 如何使 Boost.Spirit.Lex 令牌值成为匹配序列的子字符串(最好通过正则表达式匹配组)
- Boost.Test 使用正则表达式测试文件内容
- 使用 Boost::regex 进行正则表达式组匹配