Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* You are given an HTML code, written in the old non-semantic style using tags like <div id="header">, <div class="section">, etc. Your task is to write a program that converts this HTML to semantic HTML by changing tags like <div id="header"> to their semantic equivalent like <header>.
- * The non-semantic tags that should be converted are always <div>s and have either id or class with one of the following values: "main", "header", "nav", "article", "section", "aside" or "footer". Their corresponding closing tags are always followed by a comment like <!-- header -->, <!-- nav -->, etc. staying at the same line, after the tag.
- * In all converted tags you should replace multiple spaces (like <header style="color:red">) with a single space and remove excessive spaces at the end (like <footer >). */
- namespace Semantic_HTML
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- class SemanticHTML
- {
- private const string OpenTagsPattern =
- @"<(div)\s.*?((?:id|class)\s*=\s*""([a-z]+)"").*?>";
- private const string CloseTagsPattern = @"<\/div>\s+<!--\s*([a-z]+)\s*-->";
- private static HashSet<string> semanticTags;
- static void Main()
- {
- semanticTags = new HashSet<string>() { "main", "header", "nav", "article", "section", "aside", "footer" };
- string inputLine = Console.ReadLine();
- while (inputLine != "END")
- {
- if (Regex.IsMatch(inputLine, OpenTagsPattern))
- {
- ReplaceOpenTags(inputLine);
- }
- else if (Regex.IsMatch(inputLine, CloseTagsPattern))
- {
- ReplaceCloseTags(inputLine);
- }
- else
- {
- Console.WriteLine(inputLine);
- }
- inputLine = Console.ReadLine();
- }
- }
- private static void ReplaceOpenTags(string htmlLine)
- {
- MatchCollection openTags = Regex.Matches(htmlLine, OpenTagsPattern);
- foreach (Match openTag in openTags)
- {
- string semanticTag = openTag.Groups[3].Value;
- if (!semanticTags.Contains(semanticTag))
- {
- Console.WriteLine(htmlLine);
- }
- else
- {
- string divTag = openTag.Groups[1].Value;
- string attribute = openTag.Groups[2].Value;
- StringBuilder sb = new StringBuilder(openTag.Value);
- sb.Replace(divTag, semanticTag).Replace(attribute, string.Empty);
- string result = Regex.Replace(sb.ToString(), @"\s+>", ">");
- result = Regex.Replace(result, @"\s{2,}", " ");
- Console.WriteLine(htmlLine.Replace(openTag.Value, result));
- }
- }
- }
- private static void ReplaceCloseTags(string htmlLine)
- {
- MatchCollection closeTags = Regex.Matches(htmlLine, CloseTagsPattern);
- htmlLine = closeTags.Cast<Match>().Where(closeTag => semanticTags.Contains(closeTag.Groups[1].Value)).Aggregate(htmlLine, (current, closeTag) => current.Replace(closeTag.Value, string.Format("</{0}>", closeTag.Groups[1].Value)));
- Console.WriteLine(htmlLine);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement