gpt4 book ai didi

c++ - 增强::精神::保持空白

转载 作者:行者123 更新时间:2023-12-02 10:33:03 28 4
gpt4 key购买 nike

我正在使用此代码将“k1 = v1; k2 = v2; k3 = v3; kn = vn”字符串解析为映射。

    qi::phrase_parse(
begin,end,
*(*~qi::char_('=') >> '=' >> *~qi::char_(';') >> -qi::lit(';')),
qi::ascii::space, dict);

上面的代码将删除空格字符,例如“some_key = 1 2 3”变成some_key-> 123

我不知道如何删除或替换第四个参数:qi::ascii::space

基本上,我想在用'='分割后保留原始字符串(键和值)。

我对精神没有太多的经验/知识。确实需要投入时间来学习。

最佳答案

如果您不希望有船长,只需使用qi::parse而不是qi::phrase_parse即可:

qi::parse(
begin,end,
*(*~qi::char_(";=") >> '=' >> *~qi::char_(';') >> -qi::lit(';')),
dict);

但是,您可能确实想有选择地跳过空格。最简单的方法通常是拥有一个通用的船长,然后标记lexeme区域(您不允许该船长的区域):
qi::phrase_parse(
begin, end,
*(qi::lexeme[+(qi::graph - '=')]
>> '='
>> qi::lexeme[*~qi::char_(';')] >> (qi::eoi|';')),
qi::ascii::space, dict);

linked answer确实提供了更多有关如何在Qi中使用船长的技术/背景

演示时间

Live On Coliru
#include <boost/spirit/include/qi.hpp>
#include <boost/fusion/adapted/std_pair.hpp>
#include <map>
#include <iomanip>
namespace qi = boost::spirit::qi;

int main() {
for (std::string const& input : {
R"()",
R"(foo=bar)",
R"(foo=bar;)",
R"( foo = bar ; )",
R"( foo = bar ;
foo
= qux; baz =

quux
corge grault
thud

; x=)",
// failing:
R"(;foo = bar;)",
})
{
std::cout << "-------------------------\n";
auto f=begin(input), l=end(input);

std::multimap<std::string, std::string> dict;

bool ok = qi::phrase_parse(f, l,
(qi::lexeme[+(qi::graph - '=' - ';')]
>> '='
>> qi::lexeme[*~qi::char_(';')]
) % ';',
qi::space,
dict);

if (ok) {
std::cout << "Parsed " << dict.size() << " elements:\n";
for (auto& [k,v]: dict) {
std::cout << " - " << std::quoted(k) << " -> " << std::quoted(v) << "\n";
}
} else {
std::cout << "Parse failed\n";
}

if (f!=l) {
std::cout << "Remaining input: " << std::quoted(std::string(f,l)) << "\n";
}
}

}

版画
-------------------------
Parse failed
-------------------------
Parsed 1 elements:
- "foo" -> "bar"
-------------------------
Parsed 1 elements:
- "foo" -> "bar"
Remaining input: ";"
-------------------------
Parsed 1 elements:
- "foo" -> "bar "
Remaining input: "; "
-------------------------
Parsed 4 elements:
- "baz" -> "quux
corge grault
thud

"
- "foo" -> "bar "
- "foo" -> "qux"
- "x" -> ""
-------------------------
Parse failed
Remaining input: ";foo = bar;"

关于c++ - 增强::精神::保持空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61549182/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com