I'm trying to write a simple program that takes in a String
as input. If the String
matches a regex
expression then it is returned. If not, I need to go through it, find each char that is causing the problem and remove it.
The problem I'm running into is I'm using a for loop
based on the String
's length, but every time a char
is removed, the length changes, therefore shortening the for loop. Eventually leading to an index out of range error when the for loop is half way done.
Input "09fdghdghh0" - (should return '090')
public String cleanID(String id){
System.out.println("id = " + id);
//String strRegex = "[a-zA-Z]+";
String numRegex = "[0-9]+";
StringBuilder sb = new StringBuilder(id);
System.out.println(sb.toString());
if(id.matches(numRegex)){
return sb.toString();
}else{
for(int i = 0; i < id.length(); i++){
System.out.println("sb length = " + sb.length());
if(!Character.toString(sb.charAt(i)).matches(numRegex)){
System.out.println(sb.charAt(i));
sb.deleteCharAt(i);
}
}
}
return sb.toString();
Output
sb length = 11
sb length = 11
sb length = 11
f
sb length = 10
g
sb length = 9
d
sb length = 8
h
sb length = 7
sb length = 7
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 7
As you can see the loop fails half way through. Is there a better way of doing this besides a for loop? Or am I just missing something obvious?
Thanks.