0

I am working on rest API services. I need to push phone number as a string in the body of the request.

I tried following way.

String Str1=ts.phone.replaceAll('(','');
String Str2=Str1.replaceAll(')','');
String Str3=Str2.replaceAll('-','');

But I'm getting the following error

System.StringException: Invalid regex: Unclosed group near index 1

Please let me know how to convert

2 Answers 2

1

I would just strip out anything that is not a digit e.g.

String cphone = '(800) 555-1234';
String s = cphone.replaceAll('\\D','');

then if you want to format back to a US number, you can do something like this:

if (s.length() == 10) {
String sphone = '(' + s.substring(0, 3) + ') ' + s.substring(3, 6) + '-' + s.substring(6);
}
1

You need to escape the ( and )

String Str1=phone.replaceAll('\\(','');
String Str2=Str1.replaceAll('\\)','');

The following:

String phone = '(800) 555-1212';
String Str1=phone.replaceAll('\\(','');
String Str2=Str1.replaceAll('\\)','');
String Str3=Str2.replaceAll('-','');
System.debug(Str3);

Outputs

800 5551212

Some previous discussion on this located on Stackoverflow

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .