How to search a SpannableString without knowing the exact substring

I want to search a spannable string to find the index of a certain substring which I don’t know the length or exact characters of eg [size=??] where the question marks could be any characters or substring of any length. If possible I’d also like to know the length of such a string found.

(edit) Example: If a string such as "string [size=212] more string" was given I want it to return the index, so in this case 7 and the length of [size=212], in this case 10


You can accomplish this job by using Pattern and Matcher.

public class Main
    public static void main(String[] args)
        String str = "string [size=212] more string [size=212] more string here";
        Pattern pat = Pattern.compile("\[size=[0-9]+\]");
        Matcher mat = pat.matcher(str);

        int index, lastIndex = 0, length, value;

        while(mat.find()) {
            final String found =;
            value = Integer.parseInt(found.replaceAll("^\[size=|\]$", ""));
            length = found.length();
            index = str.indexOf(found, lastIndex);
            lastIndex += length;

            System.out.printf("index: %d, length: %d, string: %s, value: %d%n", index, length, found, value);


index: 7, length: 10, string: [size=212], value: 212
index: 30, length: 10, string: [size=212], value: 212