问题描述
我的原始字符串看起来像这样<@R_753_4045@ion 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。