Home > Blockchain >  How to search a SpannableString without knowing the exact substring
How to search a SpannableString without knowing the exact substring

Time:10-21

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

CodePudding user response:

You need to use regular expressions to extract the substring. Once you get it, Search match using a function indexOf , that will give you the first index of occurence of your substring.

Note:please give more details to your question

CodePudding user response:

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 = mat.group(0);
            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);
        }
    }
}

Output:

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