1

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 [email protected]

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

Thanks

2

2 Answers 2

7

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
}
0

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 - [email protected]
  {First Name}+{Last Name} - {William} + {James Chadwick Potter}
                           - {William James} + {Chadwick Potter}
                           - {William James Chadwick} + {Potter}

Your Logic wont work here

2
  • 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

You must log in to answer this question.

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