如何解决如何从一个字符串中提取多个子字符串?
我的原始字符串看起来像这样<information name="Identify" id="IdentifyButton" type="button"/>
如何从此字符串中提取3个子字符串string name_part = Identify
,string id_part="IdentifyButton"
,type_part="button"
解决方法
假设您不想使用第三方XML解析器,则只需为每个名称使用std::string
的{{1}}:
find()
根据您的容忍度添加错误检查:)
,您可以使用正则表达式提取以“ =”分隔的键/值对,并在之间使用可选的空格字符。
(\S+?)\s*=\s*([^ />]+)
[^ />]+
捕获由空格,/和>以外的字符组成的值。这将捕获带引号或不带引号的值。
然后使用std::regex_iterator(一种只读的正向迭代器),它将使用正则表达式调用std::regex_search()。这是一个示例:
#include <string>
#include <regex>
#include <iostream>
using namespace std::string_literals;
int main()
{
std::string mystring = R"(<Information name="Identify" id="IdentifyButton" type="button" id=1/>)"s;
std::regex reg(R"((\S+?)\s*=\s*([^ />]+))");
auto start = std::sregex_iterator(mystring.begin(),mystring.end(),reg);
auto end = std::sregex_iterator{};
for (std::sregex_iterator it = start; it != end; ++it)
{
std::smatch mat = *it;
auto key = mat[1].str();
auto value = mat[2].str();
std::cout << key << "_part=" << value << std::endl;
}
}
输出:
name_part="Identify"
id_part="IdentifyButton"
type_part="button"
id_part=1
这里是Demo。至少需要C ++ 11。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。