How to Split String Method in Salesforce Apex

While working as a Salesforce developer, I developed a feature that allows users to enter multiple email addresses separated by commas into a custom field.

There, I had to extract and validate each email address individually. To separate the emails, I have used the split() function to extract the emails from the string field.

In this Salesforce tutorial, I will explain several approaches for how to split string values in Salesforce Apex.

Split Strings in Salesforce Apex

To split the strings in a field, follow the steps below.

  1. Navigate to the Salesforce developer console and execute the anonymous window with “Ctrl+E”. Enter the code below in the developer console.
String emailList = 'Eva.James@mail.com, nathan.coulter@mail.com, mike.smith@mail.com';

if (emailList != null && emailList != '') {

    String[] emails = emailList.split(',');

    for (String email : emails) {
        email = email.trim();

        if (isValidEmail(email)) {
            System.debug('Valid Email: ' + email);
        } else {
            System.debug('Invalid Email: ' + email);
        }
    }
} else {
    System.debug('No emails found.');
}

public Boolean isValidEmail(String email) {
    String emailRegex = '^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$';
    Pattern pattern = Pattern.compile(emailRegex);
    Matcher matcher = pattern.matcher(email);
    return matcher.matches();
}
  1. After entering the above code, select the checkbox Open in debug and click on the Execute button.
    • In the Execution log window, select the checkbox to debug only, and then you will see the split string values in the debug console.
How to split string in Salesforce Apex

Following the above steps, we can split the string into a list using the split method in Salesforce Apex.

Split and Trim String in Salesforce Apex

To split a string and eliminate any leading or trailing whitespace, follow the steps below to split and trim a string in Salesforce Apex.

  1. Navigate to the developer console and execute the anonymous code window. Enter the code below in the anonymous code window, then click on the Execute button.
String Users = 'Steve,Ema,James';
String[] result = Users.trim().split('\\s*,\\s*');

for (String user : result) {
    System.debug(user);
}
  1. In the console log window, select the checkbox to debug only, and you will see the string split and trimmed in debug.
Split and trim String in Salesforce apex

In this way, we can split and trim a string in Salesforce Apex by following the above code.

Split a String by Dot in Salesforce Apex

In an Apex string, the dot has a meaning within regular expressions, so to remove the dot, we need to escape it with two backslashes.

  1. Navigate to the de