gpt4 book ai didi

c++ - 相同分隔符之间的多个子字符串

转载 作者:行者123 更新时间:2023-11-30 01:36:05 24 4
gpt4 key购买 nike

我是 C++ 的新手,想知道如何从单个字符串中的相同分隔符之间提取多个子字符串?

例如

"{("id":"4219","firstname":"Paul"),("id":"4349","firstname":"Joe"),("id":"4829","firstname":"Brandy")}"

我想要 ids:

4219 , 4349 , 4829

最佳答案

您可以使用正则表达式来匹配 ID:

#include <iostream>
#include <regex>

int main() {
// This is your string.
std::string s{ R"({("id":"4219","firstname":"Paul"),("id":"4349","firstname":"Joe"),"("id":"4829","firstname":"Brandy")})"};

// Matches "id":"<any number of digits>"
// The id will be captured in the first group
std::regex r(R"("id"\s*:\s*"(\d+))");

// Make iterators that perform the matching
auto ids_begin = std::sregex_iterator(s.begin(), s.end(), r);
auto ids_end = std::sregex_iterator();

// Iterate the matches and print the first group of each of them
// (where the id is captured)
for (auto it = ids_begin; it != ids_end; ++it) {
std::smatch match = *it;
std::cout << match[1].str() << ',';
}

}

See it live on Coliru

关于c++ - 相同分隔符之间的多个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563890/

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