function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
MoreThanWYSIWYGMoreThanWYSIWYG 

Need RegEx to replace 1234567890 with (123) 456-7890

I need to replace a 10 digit string - a phone number with a format like (123) 456-7890 because unforutnately, the DB a total mess.

I can do it in PHP like this:
$data = '1234567890';

if(  preg_match( '/^\d(\d{3})(\d{3})(\d{4})$/', $data,  $matches ) )
{
    $result = '('.$matches[1] . ') ' .$matches[2] . '-' . $matches[3];
    return $result;
}
Which works fine in PHP, but't I can't seem to translate it to APEX. Any help would be apprecieated.
 
Best Answer chosen by MoreThanWYSIWYG
Phillip SouthernPhillip Southern
I'm sure there are alot of ways....what I've done before is use regex to clear out any non number, then use substring to parse out the characters.

so store your value from the field and strip:
string x = contact.phone.replaceall('//D','');
//probably want to verify you still have 10 digits...and if not do cleanup if greating (leading 1's, etc)


//then do substrings
contact.phone = '(' + x.substring(0,2) + ') ' + x.substring(2,5) + '-' + x.substring(5,9);

All Answers

Phillip SouthernPhillip Southern
I'm sure there are alot of ways....what I've done before is use regex to clear out any non number, then use substring to parse out the characters.

so store your value from the field and strip:
string x = contact.phone.replaceall('//D','');
//probably want to verify you still have 10 digits...and if not do cleanup if greating (leading 1's, etc)


//then do substrings
contact.phone = '(' + x.substring(0,2) + ') ' + x.substring(2,5) + '-' + x.substring(5,9);

This was selected as the best answer
nikkeynikkey
Hi ,

I think you try this link : for your requirement.

http://www.oyecode.com/2011/07/regular-expressions-validate-phone.html
MoreThanWYSIWYGMoreThanWYSIWYG
Validating the number is no problem. What I need to do is pull the number in, then transform it to (555) 555-5555 format. I have regex to match that format, but I can't seem to take the number 5555555555 and re-construct it as (555) 555-5555. I can't find sufficient information in APEX on how to do string replace like the PHP used above.
MoreThanWYSIWYGMoreThanWYSIWYG
Philip, I will try your suggestions and let you know.