0

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.

PT_C
  • 998
  • 2
  • 23
  • 48
  • Yes. Show us what you want to replace. Maybe `replace()` or `replaceAll()` might help you. – TheLostMind Jan 30 '15 at 13:42
  • As you delete characters, `sb` gets shorter, but `id.length()` doesn't get smaller, so eventually you'll access out of index. But there should be a better way to do this in the first place, so I don't want to make this an answer. – Sebastian Redl Jan 30 '15 at 13:42

4 Answers4

3

A regex like this will help :

public static void main(String[] args) {
    String s = "09fdghdghh0";
    System.out.println(s.replaceAll("\\D", "")); // \\D removes everything which is not a number
}

O/P

090
TheLostMind
  • 34,842
  • 11
  • 64
  • 97
1

I think your best bet is to use the Pattern and Matcher classes

//Regex goes here
Pattern p = Pattern.compile("[0-9]+");
//Your string goes here
Matcher m = p.matcher(id);

if (m.find()) {
    System.out.println(m.group(1));

}

This should extract whatever text you want.

DHerls
  • 666
  • 5
  • 18
0

I would use replaceAll with a negative regex, and then compare to the original.

For instance:

String text = "10";
System.out.println(text.replaceAll("[^0-9]", " ").equals(text));
Mena
  • 45,491
  • 11
  • 81
  • 98
  • may not want to replace with a blank, perhaps "" instead. – ErstwhileIII Jan 30 '15 at 13:52
  • @ErstwhileIII the replacement in my answer is rather arbitrary. The whole idea is to test validation, i.e. whether the original `String` equals the replaced `String`. If no replacement took place (i.e. no unwanted character), then they are equal and it returns `true`. – Mena Jan 30 '15 at 14:28
0

another approach is to loop over the whole string and then add the correct values (rather than removing wrong ones) to a resultString

Viktor Mellgren
  • 3,944
  • 3
  • 36
  • 68