SpannableStringBuilder replace content with Regex
Asked Answered
B

2

7

I have the following code in which I am going to mark the contents between the curly braces with SpannableString and remove the curly braces but it gives wrong result.

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;
}

Input:

the {quic}k brown {fox} jumps {over} the lazy dog. {A Quick} {brow}nfoxjumpsoverthelazydog

Output: enter image description here

Bilestone answered 12/10, 2016 at 19:3 Comment(0)
O
17
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;
}
Orlon answered 12/10, 2016 at 21:22 Comment(4)
Thank you for your help and your precious time, nice solution, its working like charm. :-)Bilestone
Android devs: Do not confuse android.os.Pattern with java.util.regex.PatternMolecular
@kris larson How can replace the {quic}k brow[n] {fox} jumps {over} the #l#azy dog. {A Quick} {brow}n. How can mark them using different color and remove the brakets? Can you help me in this case?Neap
this might helps to solves your usecases: gist.github.com/nesquena/f2504c642c5de47b371278ee61c75124 @ShahriarNasimNafiPentahedron
B
1

If you're not against using 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;
}

If you want to use a 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;
}
Baronage answered 12/10, 2016 at 21:57 Comment(2)
Your answer is helpful and thanks for your help and time, :-)Bilestone
wouldn't this duplicated with answer from @Muhammad?Pentahedron

© 2022 - 2024 — McMap. All rights reserved.