[英]Extracting undelimited strings and integers using Boost Spirit
I'm trying to convert a string like "ABC10DEF20"
to an array ["ABC", 10, "DEF", 20]
using Boost Spirit. 我正在尝试使用Boost Spirit将类似"ABC10DEF20"
的字符串转换为数组["ABC", 10, "DEF", 20]
。 I'm not sure if "undelimited" is the right term but I want to break it up by the boundaries of integers and non-integers rather than splitting it by whitespace or another delimiting character. 我不确定“ unlimited”是否正确,但我想通过整数和非整数的边界来分解它,而不是通过空格或其他定界字符来分割它。
I've come up with code like: 我想出了类似的代码:
std::string search_str = "ABC10DEF20";
std::vector<boost::variant<std::string, unsigned int> > v;
std::string::const_iterator iter = search_str.begin();
std::string::const_iterator last = search_str.end();
bool r = parse(iter, last,
+(+(char_ - digit)|uint_),
v);
For the input "ABC10DEF20"
this results in [ 65, 66, 67, 10, 68, 69, 70, 20 ]
(no strings, just the integers and ASCII components of the string portion stored in integers). 对于输入"ABC10DEF20"
结果为[ 65, 66, 67, 10, 68, 69, 70, 20 ]
"ABC10DEF20"
[ 65, 66, 67, 10, 68, 69, 70, 20 ]
(没有字符串,只是整数部分和整数部分的ASCII部分存储在整数中)。 For the input "10"
I get [ 10 ]
as intended. 对于输入"10"
我得到了预期的[ 10 ]
。
From the output, it's apparent you're matching individual characters, not strings, and full unsigned integers. 从输出中可以明显看出,您正在匹配单个字符,而不是字符串和完整的无符号整数。
Not sure it'll fix it, but try: 不确定会解决此问题,但是请尝试:
bool r = parse(iter, last,
+(+(+char_ - digit)|uint_),
v);
(Note the added +
before char_
.) (请注意,在char_
之前添加了+
。)
The type of v
might need to change to be: std::vector<boost::variant<std::vector<char>, unsigned int> > v;
v
的类型可能需要更改为: std::vector<boost::variant<std::vector<char>, unsigned int> > v;
, and you might have to fixup the result. ,您可能必须修正结果。 Not terribly familiar with Boost Spirit; 不太熟悉Boost Spirit; I bet there's a better, cleaner, way. 我敢打赌,这是一种更好,更清洁的方式。
Final Solution: 最终解决方案:
Modify the parse expression to use: 修改解析表达式以使用:
+(as_string[+(char_ - digit)]|uint_)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.