8

I have a phone number that i need to convert to a valid format to be send to a webservice validator. The phone number should be 10 char long and should contains only digits.

For instance, I should convert

 +567 231 34 34 to 5672313434 (567)231-34-34 to 5672313434 

before sending

I have the solution which does the replacement in apex :

 String t = '+571 567 65 77'; String r = t.replaceAll('\\(',''); r = r.replaceAll('\\)',''); r = r.replaceAll('-',''); r = r.replaceAll('\\+',''); r = r.replaceAll('\\s',''); system.debug('## final result is :' + r); 

Can I obtain the result in a single line?

1
  • 1
    +567 231 34 34 is not the same phone number as 5672313434. The first is a 8 digit number in chile (I have no idea if it's a valid 8 digit number), the second is a 10 digit number in whatever country you are currently in. In most of Europe +567 231 34 34 using only digits would be 005672313434, in the US it would be 0115672313434. Commented Feb 26, 2016 at 8:58

2 Answers 2

15

Try this:

String r = t.replaceAll('[^0-9]',''); 

Explanation:

Instead of hunting for invalid characters and removing them explicitly you can specify remove all characters other than numbers.

  • ^ for not a given char
  • [0-9] for numbers ranging from 0 to 9
  • '' replace it with empty char (removes it from our string)
3

You can use ReplaceAll method

try Like this

String t = '(567)231-34-34'; String r = t.replaceAll('[^\\d]',''); system.debug('## final result is :' + r); String t1 = '+567 231 34 34'; String r1 = t1.replaceAll('[^\\d]',''); system.debug('## final result is :' + r1); 

Reference:

  • ^ - Negates character class.
  • \d - any digit character same as [0-9]

Debug logs

13:27:40:044 USER_DEBUG [3]|DEBUG|## final result is :5672313434
13:27:40:044 USER_DEBUG [7]|DEBUG|## final result is :5672313434


Another option

String t = '(567)231-34-34'; String r = t.replaceAll('[-+()s]',''); system.debug('## final result is :' + r); String t1 = '+567 231 34 34'; String r1 = t1.replaceAll('[-+()s]',''); system.debug('## final result is :' + r1); 

Reference:

  • [ ] Demarcates a character class. To interpret literally, use a backslash.
  • [abc] is a character class that means "any character from a,b or c" (a characer class may use ranges, eg [a-d] = [abcd])

Debug logs

13:26:13:004 USER_DEBUG [3]|DEBUG|## final result is :5672313434
13:26:13:004 USER_DEBUG [7]|DEBUG|## final result is :567 231 34 34

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.