markdownj icon indicating copy to clipboard operation
markdownj copied to clipboard

can't convert data to table

Open zryengytj opened this issue 10 years ago • 0 comments

example:

column1 column2
value1 value1
value2 value2
value3 value3

code is convert table

   private TextEditor doTableRules(TextEditor text) {
    String[] paragraphs;
    if (text.isEmpty()) {
        paragraphs = new String[0];
    } else {
        paragraphs = Pattern.compile("\\n").split(text.toString());
    }
    String tablesRule = "^\\s*\\-{3,}(\\|\\-{3,})+[ ]*$";
    String tdRules = "^(.*\\|.*)+$";
    boolean find = false;
    int length = 0;
    for (int i = 0; i < paragraphs.length; i++) {
        String paragraph = paragraphs[i];
        if (find) {
            if (paragraph.matches(tdRules)) {
                String td = formatTd(paragraph, length);
                paragraphs[i] = td;
            } else {
                paragraphs[i - 1] += "<tbody></table>";
                find = false;
            }
        } else {
            if (paragraph.matches(tdRules) && i + 2 < paragraphs.length) {
                String head = paragraphs[i + 1];
                String content = paragraphs[i + 2];
                if (head.matches(tablesRule) && content.matches(tdRules)) {
                    length = head.split("\\|").length;
                    String table = formatTh(paragraph, length);
                    String td = formatTd(content, length);
                    paragraphs[i] = table;
                    paragraphs[i + 1] = "<tbody>";
                    paragraphs[i + 2] = td;
                    i += 2;
                    find = true;
                }
            }
        }
    }
    return new TextEditor(join("\n", paragraphs));
}

private String formatTh(String line, int length) {
    StringBuilder tr = new StringBuilder("<table><thead><tr>\n");
    String tds[] = line.split("\\|");
    for (String td : tds) {
        tr.append("<th>").append(StringUtils.trimToNull(td)).append("</th>\n");
    }
    for (int i = tds.length; i < length; i++) {
        tr.append("<th>&nbsp;</th>\n");
    }
    tr.append("</tr>\n</thead>\n");
    return tr.toString();
}

private String formatTd(String line, int length) {
    StringBuilder tr = new StringBuilder("<tr>\n");
    String tds[] = line.split("\\|");
    for (String td : tds) {
        tr.append("<td>").append(StringUtils.trimToNull(td)).append("</td>\n");
    }
    for (int i = tds.length; i < length; i++) {
        tr.append("<td>&nbsp;</td>\n");
    }
    tr.append("</tr>\n");
    return tr.toString();
}

zryengytj avatar Aug 06 '14 02:08 zryengytj