如何在Android中使用正则表达式彩色文本 [英] How to color text using Regex in android

查看:490
本文介绍了如何在Android中使用正则表达式彩色文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有三个常规EX pression:

I have three regular expression:

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

我有一个字符串:

I have a string :

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

This is a #sample #twitter text of @tom_cruise with a link http://tom_cruise.me

我需要将这些内容与上述三个常规EX pression匹配及颜色搭配蓝色匹配的文本,并在的TextView 设定的最后文本。我怎样才能做到这一点?

I need to match this text with the above three regular expression and color the matched text with Blue and set the final text in a TextView. How can I achieve that?

这是必须提到的是我不需要 Linkify 的文字,只有着色。而且我不使用 Twitter4j 库。

It is to be mentioned that I don't need to Linkify the text, only coloring. And I am not using Twitter4j Library.

推荐答案

我换成 http://tom_cruise.me 的http:// www.google.com 。请尝试以下操作:

I replaced http://tom_cruise.me with http://www.google.com. Try the following:

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()));

这篇关于如何在Android中使用正则表达式彩色文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆