2

for this below method i can find http:// and www into text and i can create html link from that, but in this method i can only split text with \n and i want to split with \n with space, how to use regex for this action?

public static Spanned Htmlparser(String text) {
        String[] tokens = text.split("\n");
        StringBuilder sbStr = new StringBuilder();
        for (int i = 0; i < tokens.length; i++) {
            if ((tokens[i]).contains("www.")) {
                String link = " <a href=\"http://" + tokens[i] + "\">" + tokens[i] + "</a> ";
                sbStr.append(link);
            } else if ((tokens[i]).contains("http://")) {
                String link = " <a href=\"" + tokens[i] + "\">" + tokens[i] + "</a> ";
                sbStr.append(link);
            } else {
                sbStr.append(tokens[i] + " ");
            }
        }
        return Html.fromHtml(sbStr.toString());
    }

Java or android have any class for do this action without using my method?

DolDurma
  • 15,753
  • 51
  • 198
  • 377

1 Answers1

5

If you want to split a string by newline \n and space \s characters, you can use character class in regular expressions. See the following code.

 String[] tokens = text.split("[\\n\\s]");
Jagadish G
  • 671
  • 6
  • 18