function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Sam LauSam Lau 

indexOf and Substring

Hi All,

I'm attempting to text parse between two tags within the body of an incoming email.   I'm receiving an undeliverable with my tests but can't figure out how to resolve "System.StringException: Ending position out of bounds: 35"

I have my code within the email class as such:   

            //Parse email   
            String EmailStartTag = '[Email]';
            String EmailEndTag = '[/Email]';        
            integer Rstart = Body.indexOf(EmailStartTag);
            integer Rend = Body.indexOf([EmailEndTag);
            integer Rlength = Rend - Rstart;
            NPR.Email__c = Body.substring(Rstart, Rlength); 

I'm not sure why I'd reach an out of bounds since I'm simply taking the ending position integer and subtracting the starting for the length of the substring.   Any pointers would be greatly appreciated.  

Sam
Andrew GAndrew G
Hi Sam
Remember that substring, in this context, uses indexes, not lengths
substring(startIndex, endIndex)
try the following 
String Body = 'sometext [Email]xxx@yyy.net[/Email]';
System.debug('body check : ' + Body);
//Parse email   
String EmailStartTag = '[Email]';
String EmailEndTag = '[/Email]';        
Integer Rstart = Body.indexOf(EmailStartTag);
System.debug('** Rstart ' + Rstart);
Integer Rend = Body.indexOf(EmailEndTag);
System.debug('** Rend ' + Rend);
integer Rlength = Rend - Rstart;
System.debug('** Rlength ' + Rlength);
String NPR_Email = Body.substring(Rstart+7, Rend); 
System.debug('**'+ NPR_Email);

I tested in developer console, hence why all the debug statements, but it gives a clearer understanding of the method behaviours.

Note also that the Start Index will be the start point of the String '[Email]'  not the start of the actual email address.

HTH

regards
Andrew