SpannableStringBuilder用Regex替换内容

时间:2016-10-12 19:03:40

标签: java android regex spannablestring spannablestringbuilder

我有以下代码,其中我将使用 jon.properties oozie.use.system.libpath=true security_enabled=False dryrun=False nameNode=hdfs://localhost:8020 user_name=test jobTracker=localhost::8032 <workflow-app name="My_Workflow" xmlns="uri:oozie:workflow:0.5"> <start to="shell-a0a5"/> <kill name="Kill"> <message>Error [${wf:errorMessage(wf:lastErrorNode())}]</message> </kill> <action name="shell-a0a5"> <shell xmlns="uri:oozie:shell-action:0.1"> <job-tracker>${jobTracker}</job-tracker> <name-node>${nameNode}</name-node> <exec>script1.sh</exec> <file>/user/hive/script1.sh#script1.sh</file> </shell> <ok to="End"/> <error to="Kill"/> </action> <end name="End"/> 标记花括号之间的内容并删除花括号,但它会给出错误的结果。

SpannableString

输入:

String text = "the {quic}k brown {fox} jumps {over} the lazy dog. {A Quick} {brow}nfoxjumpsoverthelazydog";

tv.setText(makeSpannable(text, "\\{.*?\\}"));
public SpannableStringBuilder makeSpannable(String text, String regex) {
    SpannableStringBuilder spannable = new SpannableStringBuilder(text);
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(spannable.toString());
    while (matcher.find()) {
        String word = matcher.group();
        String abbr = word.toString().substring(1, word.length() - 1);
        spannable.setSpan(new ForegroundColorSpan(Color.RED), matcher.start(), matcher.end(),  Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.replace(matcher.start(), matcher.start() + abbr.length() , abbr);
    }
    return spannable;
}

输出: enter image description here

2 个答案:

答案 0 :(得分:8)

String text = "the {quic}k brown {fox} jumps {over} the lazy dog. {A Quick} {brow}nfoxjumpsoverthelazydog";

tv.setText(makeSpannable(text, "\\{.*?\\}"));

public SpannableStringBuilder makeSpannable(String text, String regex) {

    StringBuffer sb = new StringBuffer();
    SpannableStringBuilder spannable = new SpannableStringBuilder();

    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(text);
    while (matcher.find()) {
        sb.setLength(0); // clear
        String group = matcher.group();
        // caution, this code assumes your regex has single char delimiters
        String spanText = group.substring(1, group.length() - 1);
        matcher.appendReplacement(sb, spanText);

        spannable.append(sb.toString());
        int start = spannable.length() - spanText.length();

        spannable.setSpan(new ForegroundColorSpan(Color.RED), start, spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    sb.setLength(0);
    matcher.appendTail(sb);
    spannable.append(sb.toString());
    return spannable;
}

答案 1 :(得分:1)

如果你不反对使用html:

tv.setText(Html.fromHtml(makeStringBuffer(text, regex, Color.RED).toString()));

private StringBuffer makeColoredStringBuffer(String text, String regex, int color) {
    // create a buffer to hold the replaced string
    StringBuffer sb = new StringBuffer();
    // create the pattern matcher
    Matcher m = Pattern.compile(regex).matcher(text);
    // iterate through all matches
    while (m.find()) {
        // get the match
        String word = m.group();
        // remove the first and last characters of the match and surround with html font tag
        String abbr = String.format("<font color='#%06X'>%s</font>", (0xFFFFFF & color), word.substring(1, word.length() - 1));
        // appendReplacement handles replacing within the current match's bounds
        m.appendReplacement(sb, abbr);
    }
    // add any text left over after the final match
    m.appendTail(sb);
    return sb;
}

如果您想使用SpannableString

tv.setText(makeColoredSpannable(text, regex, Color.RED));

private SpannableStringBuilder makeColoredSpannable(String text, String regex, int color) {
    // create a spannable to hold the final result
    SpannableStringBuilder spannable = new SpannableStringBuilder();
    // create a buffer to hold the replaced string
    StringBuffer sb = new StringBuffer();
    // create the pattern matcher
    Matcher m = Pattern.compile(regex).matcher(text);
    // iterate through all matches
    while (m.find()) {
        // get the match
        String word = m.group();
        // remove the first and last characters of the match
        String abbr = word.substring(1, word.length() - 1);
        // clear the string buffer
        sb.setLength(0);
        // appendReplacement handles replacing within the current match's bounds
        m.appendReplacement(sb, abbr);
        // append the new colored section to the spannable
        spannable.append(sb);
        spannable.setSpan(new ForegroundColorSpan(color), spannable.length() - abbr.length(), spannable.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    // clear the string buffer
    sb.setLength(0);
    // add any text left over after the final match
    m.appendTail(sb);
    spannable.append(sb);
    return spannable;
}