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"


  • 1
    Can you share what you have tried so far?
    – Raul
    Mar 27, 2017 at 7:48
  • This only works where you have a naming convention used in the email of First.last@domain.com - it will break with anything like FirstLast@domain.com or Initial.Last@domain.com
    – Dave Humm
    Mar 27, 2017 at 8:10

2 Answers 2


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];
   //there is no dot or more than one dot in the substring

You Have to know that your emailid and your account name for that email id can be different.

ex -

Name - William James Chadwick Potter
     email - William123@gamil.com
  {First Name}+{Last Name} - {William} + {James Chadwick Potter}
                           - {William James} + {Chadwick Potter}
                           - {William James Chadwick} + {Potter}

Your Logic wont work here

  • That might be the case for personal email, but professional office emails are always firestname + lastname Oct 15, 2019 at 10:27
  • Not all professional names are first and last. I already had emails like first word from first name + lastname. Also, when you have two people with the same first and last name. Like, Maria Silva in countries that speaks Portuguese... It could be solved adding a number
    – m Peixoto
    Oct 15, 2019 at 10:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.