1

I have a String value from a Long Text field that contains Name/Email values. I need to extract only the names separated by a semi colon when there are multiple entries (no semi colon in the text if only one name) using Apex/String methods into another variable. Essentially strip out anything that begins with the pipe delimiter ' | ' and ends with '.com' (will always end in '.com').

Single value scenario:  John Test | jtest@none.com

Expected: John Test

Multiple values scenario: Scott Rogers | srogers@none.com; Mike Smith | msmith@none.com; Matt White | mwhite@none.com

Expected: Scott Rogers; Mike Smith; Matt White

I've tried using substring/left/right but my approach may not be correct as I'm getting a null value each time and I also believe I need an array/list to grab each entry if multiple matches.

String s1 = 'Scott Rogers | srogers@none.com; Mike Smith | msmith@none.com; Matt White | mwhite@none.com';

String s2 = s1.right(1).substringBetween(' |','.com');
1
  • 3
    Have you considered using the split method twice, first on the semicolon and then on the pipe? Jan 29 at 1:19

1 Answer 1

3

You can use two splits which will work for both single set and multiple values.

Also remember to use \\ as | gets treated as special character.

String str = 'John Test | jtest@none.com';

List<String> strings = str.split(';');
for(String eachString : strings){
    System.debug(eachString);
    List<String> nameSplits = eachString.split('\\|');
    System.debug(nameSplits.get(0).removeStart(' '));
}

output:

09:46:42.13 (14393997)|USER_DEBUG|[7]|DEBUG|John Test

String str = 'Scott Rogers | srogers@none.com; Mike Smith | msmith@none.com; Matt White | mwhite@none.com';

List<String> strings = str.split(';');
for(String eachString : strings){
    List<String> nameSplits = eachString.split('\\|');
    System.debug(nameSplits.get(0).removeStart(' '));
}

output:

09:47:29.7 (8706488)|USER_DEBUG|[6]|DEBUG|Scott Rogers
09:47:29.7 (8760453)|USER_DEBUG|[6]|DEBUG|Mike Smith
09:47:29.7 (8794915)|USER_DEBUG|[6]|DEBUG|Matt White
1
  • Thank you very much!
    – Al K
    Jan 29 at 16:42

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.