Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Recursively delete the content in the format

I use recursion to remove the unnecessary characters in a text.

EX : source ="This is demo java remove string"

regex ="This,is,java"

result ="demo remove string"

I had difficulty not provide conditions when the program stops recursive function.If there is any way to work more efficiently using recursive please tell me

public class NewClass2 {

    static String regexs[] = {"This","is", "java"};

    private static String getRecursive(String source, int level) {

        String content = "";

        if (level > regexs.length - 1) {
            return "";
        }

        level++;

        for (String regex : regexs) {
            content = source.replaceAll(regex, "");

            if (!content.equals("")) {
                content = getRecursive(content, level);
            }
        }
        return content;
    }

    public static void main(String[] args) {
        String result = getRecursive("This is demo java remove string", 0);
        System.out.println(result);
    }
}
like image 249
Ma Tâm Avatar asked Mar 23 '26 00:03

Ma Tâm


1 Answers

Your recursive method is...all wrong.

  • You shouldn't use a loop there.
  • When level > regexs.length - 1, you should return source, not ""

The method cleaned up becomes a lot simpler:

private static String getRecursive(String source, int level) {
    if (level >= regexs.length) {
        return source;
    }
    return getRecursive(source.replaceAll(regexs[level], ""), level + 1);
}

However, this still doesn't give exactly what you asked for. It gives " demo remove string" instead of "demo remove string", because the values in regexs don't contain spaces, so the spaces between words are not removed. To work around that, you could append "\\s*" to the patterns, for example:

    return getRecursive(source.replaceAll(regexs[level] + "\\s*", ""), level + 1);
like image 102
janos Avatar answered Mar 24 '26 12:03

janos