IbrahimMitko
IbrahimMitko

Reputation: 1207

Delete unwanted chars in a String Java

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.

Upvotes: 0

Views: 115

Answers (4)

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

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

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

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

Upvotes: 3

DHerls
DHerls

Reputation: 877

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.

Upvotes: 1

Mena
Mena

Reputation: 48434

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));

Upvotes: 0

Related Questions