Skip to content

Instantly share code, notes, and snippets.

@nkaretnikov
Created January 11, 2018 17:09
Show Gist options
  • Select an option

  • Save nkaretnikov/b12e58d4a5c40a6f8628f04a791a06e6 to your computer and use it in GitHub Desktop.

Select an option

Save nkaretnikov/b12e58d4a5c40a6f8628f04a791a06e6 to your computer and use it in GitHub Desktop.
attribute parser
#include <iostream>
#include <sstream>
#include <string>
#include <regex>
using namespace std;
int main()
{
ostringstream oss;
/*
oss << "<tag1 value = \"HelloWorld\">" << endl;
oss << "<tag2 name = \"Name1\">" << endl;
oss << "</tag2>" << endl;
oss << "</tag1>" << endl;
*/
oss << R"(<tag-name attribute1-name = "value1" attribute2-name = "value2">)";
oss << R"(</tag-name>)";
string s = oss.str();
/* cout << s; */
try {
string word = "[a-z\\-_A-Z0-9]+";
regex ot_rx {
"<(" + word + ")( (" + word + ") = \"(" + word + ")\")+>"
};
auto it = sregex_iterator(s.begin(), s.end(), ot_rx);
auto end = sregex_iterator();
while (it != end) {
smatch match = *it;
cout << "size: " << match.size() << endl;
if (match.size() > 1) {
cout << "tag_name: " << match[1] << endl;
}
for (size_t i = 3; i < match.size(); ++i) {
if (i % 2 != 0)
cout << "attr_name: " << match[i] << endl;
else
cout << "attr_value: " << match[i] << endl;
}
it++;
cout << endl;
}
} catch (regex_error& e) {
cerr << "Error: " << e.what() << endl;
exit(1);
}
}
@nkaretnikov
Copy link
Copy Markdown
Author

output:

size: 5
tag_name: tag-name
attr_name: attribute2-name
attr_value: value2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment