使用提升精神 x3 解析逗号分隔的 0 或多个列表
Parsing a comma separated 0 or more list using boost spirit x3
我经常需要在boost spirit x3中解析逗号分隔0 or more list
。我知道将1 or more list
解析为std::vector
的%-operator
.当我需要0 or more list
时,我目前是这样-(element_parser % separator)
这样做的,它可以做我想做的,但解析成一个boost::optional<std::vector>
,这不是我想要的东西。那么我怎样才能制作一个解析器,它使用 boost spirit x3 将逗号分隔0 or more list
解析为普通的 std::vector。
也许我错过了一些东西,但使用-
对我来说是预期的:
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
#include <boost/spirit/home/x3.hpp>
namespace x3 = boost::spirit::x3;
const x3::rule<class number_list_tag, std::vector<int>> integer_list = "integer_list";
const auto integer_list_def = -(x3::int_ % ',');
BOOST_SPIRIT_DEFINE(integer_list);
template <typename T>
std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec)
{
bool first = true;
os << '[';
for (const T& x : vec)
{
if (first)
first = false;
else
os << ", ";
os << x;
}
os << ']';
return os;
}
std::vector<int> parse(const std::string& src)
{
std::vector<int> result;
auto iter = src.begin();
bool success = x3::phrase_parse(iter, src.end(), integer_list, x3::space, result);
if (!success || iter != src.end())
throw std::runtime_error("Failed to parse");
else
return result;
}
int main()
{
std::cout << """:t" << parse("") << std::endl;
std::cout << ""5":t" << parse("5") << std::endl;
std::cout << ""1, 2, 3":t" << parse("1, 2, 3") << std::endl;
}
输出为:
"": []
"5": [5]
"1, 2, 3": [1, 2, 3]
相关文章:
- Pybind11:将元组列表从Python传递到C++
- 从链接列表c++中删除一个项目
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- C++如何通过用户输入删除列表元素
- 读取文件的最后一行并输入到链接列表时出错
- 复制列表初始化的隐式转换的等级是多少
- 如何将 txt 文件中的行分隔为组件C++
- 无法通过空白将文本文件行分隔为矢量
- 使用 STD 正则表达式标记逗号分隔的列表
- C++:使用声明中的逗号分隔列表
- 使用提升精神 x3 解析逗号分隔的 0 或多个列表
- C++中将不同类型的变量列表连接到逗号分隔字符串的最快方法是什么?
- 将整数列表打印为逗号分隔的数字列表,每行最多 10 个
- 读取以行分隔的字符串列表时跳过空行
- 使用语义操作分析逗号分隔的范围和数字列表
- 使用Boost Spirit Qi解析分隔的令牌列表
- 为什么我会超时(使用sstream解析用逗号分隔的整数列表)
- 为什么在逗号分隔的值列表周围放括号会改变赋值
- 在C语言中,用逗号分隔的值列表(用括号括起来)是什么意思?A = (1,2,3);
- 输出以空格分隔的列表