gpt4 book ai didi

c++ - 如何将字符串解析为 std::map 并验证其格式?

转载 作者:太空狗 更新时间:2023-10-29 23:38:43 26 4
gpt4 key购买 nike

我想解析像 "{{0, 1}, {2, 3}}" 这样的字符串进入std::map .我可以使用 <regex> 编写一个用于解析字符串的小函数库,但我不知道如何检查给定的字符串是否为有效格式。如何验证字符串的格式?

#include <list>
#include <map>
#include <regex>
#include <iostream>

void f(const std::string& s) {
std::map<int, int> m;
std::regex p {"[\\[\\{\\(](\\d+),\\s*(\\d+)[\\)\\}\\]]"};
auto begin = std::sregex_iterator(s.begin(), s.end(), p);
auto end = std::sregex_iterator();
for (auto x = begin; x != end; ++x) {
std::cout << x->str() << '\n';
m[std::stoi(x->str(1))] = std::stoi(x->str(2));
}
std::cout << m.size() << '\n';
}

int main() {
std::list<std::string> l {
"{{0, 1}, (2, 3)}",
"{{4, 5, {6, 7}}" // Ill-formed, so need to throw an excpetion.
};
for (auto x : l) {
f(x);
}
}

注意:我觉得没有必要使用 regex解决这个问题。任何类型的解决方案,包括一些通过减去子字符串来立即验证和插入的方法,都将受到赞赏。

最佳答案

在我看来,基于 Spirit 的解析器总是更加健壮和可读。用 Spirit 解析也更有趣 :-)。所以,除了@Aleph0 的回答,我还想提供一个 compact solution based on Spirit-X3 :

#include <string>
#include <map>
#include <iostream>
#include <boost/fusion/adapted/std_pair.hpp>
#include <boost/spirit/home/x3.hpp>

int main() {
std::string input ="{{0, 1}, {2, 3}}";
using namespace boost::spirit::x3;
const auto pair = '{' > int_ > ',' > int_ > '}';
const auto pairs = '{' > (pair % ',') > '}';
std::map<int, int> output;
// ignore spaces, tabs, newlines
phrase_parse(input.begin(), input.end(), pairs, space, output);

for (const auto [key, value] : output) {
std::cout << key << ":" << value << std::endl;
}
}

请注意,我使用了运算符 >,意思是“预期”。因此,如果输入与预期不符,Spirit 会抛出异常。如果您更喜欢静默失败,请改用运算符 >>>

关于c++ - 如何将字符串解析为 std::map 并验证其格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56680371/

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