[SalesForce] regex too complicated error when using split function for less than 1M characters

I am working with an attachment in Salesforce.
this is a text file with 7291 rows and each row has 94 columns.

I am able to read this attachment record as "Attachment".
I am also able to convert "Attachment" to String using Body.ToString()
function of the Attachment class.
After this I try to split the string using newline character using split function.

Here is where I get "regex too complicated" error.

I assume this error is because of the size of the string.
So I am trying to come up with a way to parse string without using split
function.

I can do this using SubString function in a loop but for this I need
to know what is the string length to be able to stop the loop.

But I don't see a way to get string size in apex.

How can we do this ? Also any idea why Split is failing for string which has less than 1M characters ?

Below is the code –

public PageReference validateFile()
{
    //need to do validation
    String errormessage = '';
    validationPassed = true;

if(attachmentProperty != null && attachmentProperty.Body != null )
    {
        string attachmentBodyString = attachmentProperty.Body.toString();
    //above string populated correctly with attachment content

        List<string> modifiedfileLinesList = new List<string>();
        List<string> fileLinesList = attachmentBodyString.split('\n');

    //above split function is throwing an error

    //some logic here
}


}

Any insight into this would be great.

Best Answer

if(attachmentProperty != null && attachmentProperty.Body != null ) { string attachmentBodyString = attachmentProperty.Body.toString(); //above string populated correctly with attachment content

    List<string> modifiedfileLinesList = new List<string>();
    List<string> fileLinesList = new List<String>();
    while(attachmentBodyString != '')
    {
         fileLinesList.add(attachmentBodyString.substring(0,attachmentBodyString.firstIndexOf('\n')));
         attachmentBodyString = attachmentBodyString.substring(attachmentBodyString.firstIndexOf('\n'), attachmentBodyString.length());
    }

attachmentBodyString.split('\n');

//above split function is throwing an error

//some logic here

}

Related Topic