[SalesForce] Catch Regex too complicated when splitting a string in salesforce

I have created a function wherein I split a string from the csv filecsvAsString.split('\n')
. It is working when the string is not so big. But when I try to split a very large string, an error will occur

regex too complicated

what I want to do is to catch if an error occur during the split process. How will I do it ? I've tried to use try and catch but the problem still occur. Is there any other possible solution?

Best Answer

Not a catch per say (IIRC you cannot catch it, especially if Catch Exception did not work) but will solve the problem of regex to complex, use a custom iterator:

CLASS

public with sharing class Utility_RowIterator implements Iterator<String>, Iterable<String>
{
   private String m_Data;
   private Integer m_index = 0;
   private String m_rowDelimiter = '\n';
    
   public Utility_RowIterator(String fileData)
   {
      m_Data = fileData; 
   }
   public Utility_RowIterator(String fileData, String rowDelimiter)
   {
      m_Data = fileData; 
      m_rowDelimiter = rowDelimiter;
   }
    
   public Boolean hasNext()
   {
      return m_index < m_Data.length() ? true : false;
   }
   public String next()
   {     
      Integer key = m_Data.indexOf(m_rowDelimiter, m_index);
       
      if (key == -1)
        key = m_Data.length();
             
      String row = m_Data.subString(m_index, key);
      m_index = key + 1;
      return row;
   }
   public Iterator<String> Iterator()
   {
      return this;   
   }
}

CODE

Utility_RowIterator r = New Utility_RowIterator(csv,'\n'); //Replace \n with whatever delineates your row

String firstRow;
if(r.hasNext()) firstRow = r.next();

TEST CLASS (Provided by @KateFedchenko)

@isTest static void testUtilityRowIterator() {
    String csv = '"FirstName", "LastName"\n"TestName1", "Test1"\n"TestName2", "Test2"';
    List<String> names = new List<String>();
    UtilityRowIterator rowIterator = new UtilityRowIterator(csv, '\n');
    Iterator<String> iterator = rowIterator.iterator();
    while (iterator.hasNext()) {
        names.add(iterator.next());
    }
    System.assertEquals('"TestName1", "Test1"', names[1]);
}
Related Topic