Skip to content

Instantly share code, notes, and snippets.

@martin-minarik
Created June 12, 2024 00:12
Show Gist options
  • Save martin-minarik/d94281131b6c591468a1251969425b3e to your computer and use it in GitHub Desktop.
Save martin-minarik/d94281131b6c591468a1251969425b3e to your computer and use it in GitHub Desktop.
HTML tag parity checking
#include <iostream>
#include <stack>
#include <regex>
using namespace std;
void print_tags(string text);
bool is_start_tag(const string &element);
bool check_html_tags_parity(string text);
int main()
{
cout << boolalpha;
// Demonstration 1
{
const string html_test_string = "<body>\n"
" <h1> foobar </h1>\n"
"</body>\n";
print_tags(html_test_string);
cout << check_html_tags_parity(html_test_string) << endl;
}
cout << endl;
// Demonstration 2
{
const string html_test_string = "<body>\n"
" <h1> foobar </h1>\n";
print_tags(html_test_string);
cout << check_html_tags_parity(html_test_string) << endl;
}
return 0;
}
void print_tags(string text)
{
smatch match;
regex regex_("</?.+?>");
while (regex_search(text, match, regex_))
{
cout << match[0].str() << " ";
text = match.suffix();
}
cout << endl;
}
bool is_start_tag(const string &element)
{
return element[1] != '/';
}
bool check_html_tags_parity(string text)
{
stack<string> stack_;
smatch match;
regex regex_("</?(.+?)>");
while (regex_search(text, match, regex_))
{
string element = match[0].str();
string tag = match[1].str();
if (is_start_tag(element))
stack_.push(tag);
else
{
if (!stack_.empty())
{
if (stack_.top() == tag)
stack_.pop();
else
return false;
}
else
return false;
}
text = match.suffix();
}
return stack_.empty();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment