[SalesForce] How to get first and last name from an email address

I am trying to get the first and last name from email address field in Apex code but I am only getting the first name not able to get the last name can anyone please help me.

For an example
First.last@abc.com

I need to get a string which will be having "First last"

Thanks

Best Answer

If your requirement is to substring the left part before the @ and then split this substring using the . character, you can easily do this with the String class.

String leftPart = email.substringBefore('@');
String[] leftPartSplitted = leftPart.split('\\.');
//we check if there's one dot in the substring
if(leftPartSplitted.size() == 2){
   String firstName = leftPartSplitted[0];
   String lastName = leftPartSplitted[1];
}else{
   //there is no dot or more than one dot in the substring
}
Related Topic