Skip to content

Instantly share code, notes, and snippets.

@jflopezfernandez
Last active May 7, 2018 11:12
Show Gist options
  • Save jflopezfernandez/3a512f995fce0c8bb7c52f346be31967 to your computer and use it in GitHub Desktop.
Save jflopezfernandez/3a512f995fce0c8bb7c52f346be31967 to your computer and use it in GitHub Desktop.
Matching Subexpressions (XML)
/** In this example, the regular expression /<(.*)>(.*)</(\1)>/ searches for
* any number of any characters in angle brackets, any number of any characters
* in after the angle brackets, and then finally a forward slash followed by
* any number of any characters, again in angle brackets. This thus forms the
* XML tags search expression.
*
*/
#include <iostream>
#include <regex>
#include <string>
int main(int argc, char *argv[])
{
const std::string data = "<Person>\n"
" <FirstName>John</FirstName>\n"
" <LastName>Meier</LastName>\n"
"</Person>\n";
std::regex tagRegex("<(.*)>(.*)</(\\1)>");
// Iterate over all matches
auto pos = data.cbegin();
auto end = data.cend();
std::smatch match;
for (; std::regex_search(pos, end, match, tagRegex); pos = match.suffix().first)
{
std::cout << "Match: " << match.str() << "\n";
std::cout << " Tag: " << match.str(1) << "\n";
std::cout << "Value: " << match.str(2) << "\n\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment