Convert plain text to HTML text in Java

前端 未结 6 647
-上瘾入骨i
-上瘾入骨i 2020-12-05 10:53

I have java program, which will receive plain text from server. The plain text may contain URLs. Is there any Class in Java library to convert plain text to HTML text? Or an

6条回答
  •  感动是毒
    2020-12-05 11:37

    Just joined the coded from all answers:

    private static String txtToHtml(String s) {
            StringBuilder builder = new StringBuilder();
            boolean previousWasASpace = false;
            for (char c : s.toCharArray()) {
                if (c == ' ') {
                    if (previousWasASpace) {
                        builder.append(" ");
                        previousWasASpace = false;
                        continue;
                    }
                    previousWasASpace = true;
                } else {
                    previousWasASpace = false;
                }
                switch (c) {
                    case '<':
                        builder.append("<");
                        break;
                    case '>':
                        builder.append(">");
                        break;
                    case '&':
                        builder.append("&");
                        break;
                    case '"':
                        builder.append(""");
                        break;
                    case '\n':
                        builder.append("
    "); break; // We need Tab support here, because we print StackTraces as HTML case '\t': builder.append("     "); break; default: builder.append(c); } } String converted = builder.toString(); String str = "(?i)\\b((?:https?://|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'\".,<>?«»“”‘’]))"; Pattern patt = Pattern.compile(str); Matcher matcher = patt.matcher(converted); converted = matcher.replaceAll("$1"); return converted; }

提交回复
热议问题