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.chenandFirst domain: example.com[email protected]→Second local: adminandSecond domain: io.devmaya.chen.example.com→Third at index: -1andThird valid: false
Requirements:
- Cut each good email at its own
@. UseindexOfwithsubstring, or thesubstringBeforeandsubstringAftershortcuts. - Print
First local:andFirst domain:for case A. - Print
Second local:andSecond domain:for case B. - Don't cut the third email. Print its
@position asThird at index:, andThird 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.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.