LardaX

SemanticHtml

Feb 14th, 2017
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6.  
  7. public class SemanticHtmlRetry {
  8.     public static void main(String[] args) throws IOException {
  9.         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  10.         String openingRegex = "<div((\\s+\\S+)*?)\\s*(id|class)\\s*=\\s*\"(?<tag>\\w+)\"((\\s+\\S+)*?)\\s*>";
  11.         String closingRegex = "<\\/div>\\s*<!--\\s*(?<tag>\\w+)\\s*-->";
  12.         Pattern openingPattern = Pattern.compile(openingRegex);
  13.         Pattern closingPattern = Pattern.compile(closingRegex);
  14.  
  15.         String line;
  16.  
  17.         while (!"END".equals(line = reader.readLine())) {
  18.             Matcher openingMatch = openingPattern.matcher(line);
  19.             Matcher closingMatch = closingPattern.matcher(line);
  20.             StringBuilder currentTag = new StringBuilder();
  21.  
  22.             if (openingMatch.find()) {
  23.                 String beforeTag = openingMatch.group(1);
  24.                 String afterTag = openingMatch.group(5);
  25.                 currentTag.append("<").append(openingMatch.group("tag")).append(beforeTag).append(afterTag).append(">");
  26.  
  27.                 String spaceRegex = "(\\s)+";
  28.                 Pattern spacePattern = Pattern.compile(spaceRegex);
  29.                 Matcher spaceMatch = spacePattern.matcher(currentTag);
  30.                 String result = currentTag.toString();
  31.  
  32.                 if (spaceMatch.find()) {
  33.                     result = spaceMatch.replaceAll("$1");
  34.                 }
  35.  
  36.  
  37.                 System.out.println(result);
  38.             } else if (closingMatch.find()) {
  39.                 currentTag.append("</").append(closingMatch.group("tag")).append(">");
  40.                 System.out.println(currentTag);
  41.             } else {
  42.                 System.out.println(line);
  43.             }
  44.         }
  45.  
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment