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);
}
}
Your recursive method is...all wrong.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With