我正在尝试使用递归方法在字符串上查找标签,将其删除,然后为找到的文本着色。但是我的代码无法返回正确的字符串,因为从字符串中删除标签以使其着色后,删除了所有具有正确位置的标签

我的递归方法工作正常,但是在返回字符串后,我遇到了问题,我的字符串最后带有标签!!

String str     = "11111111<mft:A>2222222</mft:A>1111111<mft:S>33333333</mft:S> <mft:A>99999</mft:A><mft:S>v44444444/mft:S><mft:R>555555</mft:R><mft:S>6666666</mft:S><mft:A>7777777</mft:A>111111";


String nonTags = extractAyehTags(str);
//result is: 1111111122222221111111<mft:S>33333333</mft:S> <mft:A>99999</mft:A><mft:S>v44444444/mft:S><mft:R>555555</mft:R><mft:S>6666666</mft:S><mft:A>7777777</mft:A>111111

Spannable WordToSpan = new SpannableStringBuilder(nonTags);

for (int p = 0; p < ayeHaPositions.size(); p++) {
    WordToSpan.setSpan(new ForegroundColorSpan(Color.BLUE), ayeHaPositions.get(p).getStart(), ayeHaPositions.get(p).getEnd(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}

welcome_message.setText(WordToSpan);


我的递归方法,用于删除标签并获取找到的文本位置

private String extractAyehTags(String str) {
    String  nonTags    = str;
    Pattern mftA_REGEX = Pattern.compile("<mft:A>(.+?)</mft:A>");

    Matcher matcher = mftA_REGEX.matcher(str);

    if (matcher.find()) {
        String found = matcher.group(1);

        int start = str.indexOf(found.trim());

        ayeHaPositions.add(new AyehaTagsInformation(start - ("<mft:A>".length()), (start + found.length()) - ("</mft:A>".length()), found));
        nonTags = str.replace("<mft:A>" + matcher.group(1) + "</mft:A>", matcher.group(1));

        extractAyehTags(nonTags);
    }
    return nonTags;
}

最佳答案

更改递归方法后解决的问题:

private String extractAyehTags(String str) {
    nonTags = str;
    Pattern mftA_REGEX = Pattern.compile("<mft:A>(.+?)</mft:A>");

    Matcher matcher = mftA_REGEX.matcher(str);

    if (matcher.find()) {
        String found = matcher.group(1);

        int start = str.indexOf(found);

        ayeHaPositions.add(new AyehaTagsInformation(start - ("<mft:A>".length()), (start + found.length()+1) - ("</mft:A>".length()), found));
        nonTags = str.replace("<mft:A>" + matcher.group(1) + "</mft:A>", matcher.group(1));

        return extractAyehTags(nonTags);
    }
    return nonTags;
}


问题是这条线:

extractAyehTags(nonTags);


我将其更改为:

return extractAyehTags(nonTags);

10-04 10:59