content: import java.util.regex.*;
  public class Solution {
      Stack < String > stack = new Stack < > ();
      boolean contains_tag = false;
      public boolean isValidTagName(String s, boolean ending) {
          if (ending) {
              if (!stack.isEmpty() && stack.peek().equals(s))
                  stack.pop();
              else
                  return false;
          } else {
              contains_tag = true;
              stack.push(s);
          }
          return true;
      }
      public boolean isValid(String code) {
          String regex = "<[A-Z]{0,9}>([^<]*(<((\\/?[A-Z]{1,9}>)|(!\\[CDATA\\[(.*?)]]>)))?)*";
          if (!Pattern.matches(regex, code))
              return false;
          for (int i = 0; i < code.length(); i++) {
              boolean ending = false;
              if (stack.isEmpty() && contains_tag)
                  return false;
              if (code.charAt(i) == '<') {
                  if (code.charAt(i + 1) == '!') {
                      i = code.indexOf("]]>", i + 1);
                      continue;
                  }
                  if (code.charAt(i + 1) == '/') {
                      i++;
                      ending = true;
                  }
                  int closeindex = code.indexOf('>', i + 1);
                  if (closeindex < 0 || !isValidTagName(code.substring(i + 1, closeindex), ending))
                      return false;
                  i = closeindex;
              }
          }
          return stack.isEmpty();
      }
  }