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.


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){
    } else if(String.isNotBlank(sequence)){
        List<String> brakets = sequence.split('');
        for(String bracket :brakets){

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)


split(' ') method will do the work.

String spl = 'Hello v ivek { } ';
String[] sp2 = spl.split(' ');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.