0

Is there a better way to remove all illegal characters from a String than my solution? Maybe a lambda expression or regular expression? In this case I only want to keep 0 - 9, A - Z, a - z.

String iban = "DE07 1234 1234 1234 1234 12";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < iban.length(); i++) {
    int val = iban.charAt(i);
    if (    (val >= '0' && val <= '9')          // 0 - 9
            || (val >= 'A' && val <= 'Z')       // A - Z
            || (val >= 'a' && val <= 'z')) {    // a - z
        sb.append(val);
    }
}
iban = sb.toString();

2 Answers2

4

It should leave only letters a-z, A-Z and numbers 0-9. Basically use a regex for replace

iban = iban.replaceAll("[^a-zA-Z0-9]","");
Morph21
  • 859
  • 4
  • 17
  • You should probably add an assignment, since merely calling replaceAll without making use of the returned value will have no effect at all. – VGR Dec 14 '21 at 15:42
  • @VGR yes, you are right. I did correct it – Morph21 Dec 15 '21 at 07:28
2

Yes: with a regexp:

String iban = "DE07 1234 1234 1234 1234 12";
iban = iban.replaceAll("[^0-9A-Za-z]", "");
Maurice Perry
  • 8,497
  • 2
  • 10
  • 23