如何在Android中使用正则表达式彩色文本文本、彩色、如何在、正则表达式

2023-09-06 18:32:24 作者:戒不掉的寂寞

我有三个常规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()));
 
精彩推荐
图片推荐