ApexSensei

Drills › Write Apex

Parse an email

Write Apex · Beginner · 12 min · Runs in your Salesforce Developer org · Free

Scenario. An integration stores the local part (before the `@`) and the domain in separate fields, and some imported emails are broken.

Split Contact emails at the @ into mailbox and domain, and handle an email with no @ safely.

What you will learn

indexOf('@') finds the @. substring(start, end) returns text from start up to but not including end. substring(start) is the rest. Shortcuts: substringBefore('@'), substringAfter('@'). contains('@') is true when the character appears anywhere.

Integer atIndex = value.indexOf('@');
String left = value.substring(0, atIndex);
String right = value.substring(atIndex + 1);

Gotcha. With no @, indexOf returns -1 and substring(0, -1) throws. Check first.

The task

Split two Contact emails into the part before the @ and the part after it, then spot an email with no @.

Examples:

  • [email protected] → First local: maya.chen and First domain: example.com
  • [email protected] → Second local: admin and Second domain: io.dev
  • maya.chen.example.com → Third at index: -1 and Third valid: false

Requirements:

  1. Cut each good email at its own @. Use indexOf with substring, or the substringBefore and substringAfter shortcuts.
  2. Print First local: and First domain: for case A.
  3. Print Second local: and Second domain: for case B.
  4. Don't cut the third email. Print its @ position as Third at index:, and Third valid: (true only if it has an @).

Starter code

String email = '[email protected]';
Integer atIndex;
String localPart;
String domain;

// Case A: [email protected]

// Case B: [email protected]
email = '[email protected]';

// Case C: no @ at all
email = 'maya.chen.example.com';

When it passes

Both good emails split at their own @. The third email has no @, so its index is -1 and it is never cut.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Clean a Contact name · Split and join text ›