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

Expected: John Test

Multiple values scenario: Scott Rogers | [email protected]; Mike Smith | [email protected]; Matt White | [email protected]

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 | [email protected]; Mike Smith | [email protected]; Matt White | [email protected]';

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, 2022 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 | [email protected]';

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 | [email protected]; Mike Smith | [email protected]; Matt White | [email protected]';

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, 2022 at 16:42

You must log in to answer this question.

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