在Java中将纯文本转换为HTML文本

问题描述:

我有java程序,它将从服务器接收纯文本。纯文本可能包含URL。 Java库中是否有任何类将纯文本转换为HTML文本?还是其他任何图书馆?如果没有那么解决方案是什么?

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 any other library? If there are not then what is the solution?

我找到了一个使用模式匹配的解决方案。这是我的代码 -

I found a solution using pattern matching. Here is my code -

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(plain);
plain = matcher.replaceAll("<a href=\"$1\">$1</a>");

以下是输入和输出 -

And Here are the input and output -

输入文本是变量普通

some text and then the URL http://www.google.com and then some other text.

输出:

some text and then the URL <a href="http://www.google.com">http://www.google.com</a> and then some other text.