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();
Christoph S.
  • 585
  • 3
  • 16
  • 2
    Define "better": more performant? more concise? more readable? more compatible? – Izruo Dec 14 '21 at 13:23
  • Maybe a way where I needn't iterate over each character – Christoph S. Dec 14 '21 at 13:25
  • 2
    Does this answer your question? [Replacing all non-alphanumeric characters with empty strings](https://stackoverflow.com/questions/1805518/replacing-all-non-alphanumeric-characters-with-empty-strings) – Wing Kui Tsoi Dec 14 '21 at 13:25

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
  • 1,111
  • 6
  • 18
  • 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
  • 9,261
  • 2
  • 12
  • 24