如何在android中使用Regex为文本着色

Kai*_*dul 4 java regex android

我有三个正则表达式:

Pattern mentionPattern = Pattern.compile("(@[A-Za-z0-9_-]+)");
Pattern hashtagPattern = Pattern.compile("(#[A-Za-z0-9_-]+)");
Pattern urlPattern = Patterns.WEB_URL;
Run Code Online (Sandbox Code Playgroud)

我有一个字符串:

这是一个#sample #twitter的文本@tom_cruise的链接http://tom_cruise.me

我需要将此文本与上面的三个正则表达式匹配,并将匹配的文本用蓝色着色,并将最终文本设置为TextView.我怎样才能做到这一点?

值得一提的是,我不需要Linkify文字,只需要着色.而且我没有使用Twitter4j图书馆.

Vik*_*ram 7

我替换http://tom_cruise.mehttp://www.google.com.请尝试以下方法:

String a = "This is a #sample #twitter text of @tom_cruise with a link http://www.google.com";

Pattern mentionPattern = Pattern.compile("(@[A-Za-z0-9_-]+)");
Pattern hashtagPattern = Pattern.compile("(#[A-Za-z0-9_-]+)");
Pattern urlPattern = Patterns.WEB_URL;

StringBuffer sb = new StringBuffer(a.length());
Matcher o = hashtagPattern.matcher(a);

while (o.find()) {
    o.appendReplacement(sb, "<font color=\"#437C17\">" + o.group(1) + "</font>");
}
o.appendTail(sb);

Matcher n = mentionPattern.matcher(sb.toString());
sb = new StringBuffer(sb.length());

while (n.find()) {
    n.appendReplacement(sb, "<font color=\"#657383\">" + n.group(1) + "</font>");
}
n.appendTail(sb);

Matcher m = urlPattern.matcher(sb.toString());
sb = new StringBuffer(sb.length());

while (m.find()) {
    m.appendReplacement(sb, "<font color=\"#EDDA74\">" + m.group(1) + "</font>");
}
m.appendTail(sb);

textView.setText(Html.fromHtml(sb.toString()));
Run Code Online (Sandbox Code Playgroud)