Android:在字符串中着色匹配

时间:2014-08-03 10:00:36

标签: java android regex pattern-matching

我想为以#,+或@开头的所有单词着色。我找到了匹配单词和SpannableString的颜色子串的解决方案,但它不能正常工作。只有最后一场比赛变色,其他比赛保持无色,但我无法找到错误。

public static SpannableStringBuilder colorTags(Context cxt, String text){
    final Pattern hashtag = Pattern.compile("#\\w+");
    final Pattern at = Pattern.compile("(\\s|\\A)@(\\w+)");
    final Pattern name = Pattern.compile("(\\s|\\A)\\+(\\w+)");

    final SpannableStringBuilder spannable = new SpannableStringBuilder(text);

    final ForegroundColorSpan at_color = new ForegroundColorSpan(cxt.getResources().getColor(R.color.orange));
    final ForegroundColorSpan hash_color = new ForegroundColorSpan(cxt.getResources().getColor(R.color.light_blue));
    final ForegroundColorSpan name_color = new ForegroundColorSpan(cxt.getResources().getColor(R.color.green));

    final Matcher matcher = hashtag.matcher(text);
    final Matcher at_matcher = at.matcher(text);
    final Matcher name_matcher = name.matcher(text);


    while (matcher.find()) {
        spannable.setSpan(
                hash_color, matcher.start(), matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }

    while (at_matcher.find()) {
        spannable.setSpan(
                at_color, at_matcher.start(), at_matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }

    while (name_matcher.find()) {
        spannable.setSpan(
                name_color, name_matcher.start(), name_matcher.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        );
    }
    return spannable;
}

1 个答案:

答案 0 :(得分:1)

每个跨度都需要一个新对象,否则它将被移动并最终在最后一个跨度上结束。

while (matcher.find()) {
    ForegroundColorSpan hash_color =
        ForegroundColorSpan(cxt.getResources().getColor(R.color.light_blue));
    spannable.setSpan( hash_color, matcher.start(), matcher.end(),
                       Spanned.SPAN_EXCLUSIVE_EXCLUSIVE );
}

其他循环相同。