CHarris
CHarris

Reputation: 2793

Android : replacing characters in a string

In my phonebook on my mobile I have all sorts of contacts like :

+(353) 085 123 45 67
00661234567
0871234567
(045)123456

I'm putting them all into E.164 format which I've largely completed but the question I need resolved is this:

How can I strip all characters (including spaces) except numbers in my string, apart from the first character if it is '+' or a number ?

string phoneNumberofContact;

So for example the cases above would look like :

+3530851234567
00661234567
0871234567
045123456

Upvotes: 0

Views: 979

Answers (2)

Ben P.
Ben P.

Reputation: 54194

Update

To handle + only in the first position, you could do:

boolean starsWithPlus = input.charAt(0) == '+';
String sanitized = input.replaceAll("[^0-9]", "");

if (startsWithPlus) {
    sanitized = "+" + sanitized;
}

So basically I'm checking to see if it starts with plus, then stripping out everything but digits, and then re-adding the plus if it was there.

Original

Assuming you only want to keep + or digits, a simple regex will work, and String provides the replaceAll() method to make it even easier.

String sanitized = input.replaceAll("[^+0-9]", "");

Upvotes: 2

M Y
M Y

Reputation: 1832

This method would do the trick

public String cleanPhoneDigits(String phonenum) {
StringBuilder builder = new StringBuilder();
if (phonenum.charAt(0).equals('+') {
     builder.append('+');
}
for (int i = 1; i < phonenum.length(); i++) {
    char c = phonenum.charAt(i);
    if (Character.isDigit(c)) {
        builder.append(c);
    }
}
return builder.toString();
}

Upvotes: 1

Related Questions