[SalesForce] How To Split String by space and store each character or substring in array

How To Split String by space and store each character or substring in array
I have: String – '(1 OR 2) AND 3'
I need in this way:

String [] filterLogicSplittedbySpace=new String[]{'(', '1', 'OR', '2', ')', 'AND', '3'};

Please guide.

Best Answer

Usage of String.split method doesn't fit your requirements, as you will have '(1' first element and '2)' third element. Use String.splitByCharacterType method.

Splits the current String by character type and returns a list of contiguous character groups of the same type as complete tokens.

This will split and extract correct parts of your string. Brackets are split from numbers

String str = '(1 OR 2) AND 3';
List<String> groupedResult = str.splitByCharacterType();
List<String> filterLogicSplitbySpace= new List<String>();
for(String sequence :groupedResult){
    if(sequence.isAlphanumeric()){
        filterLogicSplitbySpace.add(sequence);
    } else if(String.isNotBlank(sequence)){
        List<String> brakets = sequence.split('');
        for(String bracket :brakets){
            filterLogicSplitbySpace.add(bracket);
        }
    }
}
System.debug(filterLogicSplitbySpace);

Debug result is:

DEBUG|((, 1, OR, 2, ), AND, 3)

this code also works for more complicated conditions, like String str = '((1 OR 2) AND 3) OR 4';

Debug is:

DEBUG|((, (, 1, OR, 2, ), AND, 3, ), OR, 4)