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
bluecapbluecap 

How to split a string containing square brackets..?

Hi all,

Im trying to split a string that has a mulitple sets of text enclosed in square brackets. For some reason its not splitting them like I think that it should.. Can anyone tell what Im doing incorrectly?

String tmpBody = 'TestBamo[#taskdate:2016-11-15 00:00:00][#hitcriteria:Proactively schedule a branch visit]';
String[] bodyList = tmpBody.split('\\\[(.*?)\\]'); 
for(String s : bodyList){
    system.debug('------>'+s);    
}

Which returns...

s[0] = TestBamo

I would think this should return the following...

s[0] = [#taskdate:2016-11-15 00:00:00]
s[1] = [#hitcriteria:Proactively schedule a branch visit]

 
Nagendra ChinchinadaNagendra Chinchinada
Hi,

If u need output like this, try below code
|DEBUG|------>TestBamo
|DEBUG|------>[#taskdate:2016-11-15 00:00:00]
|DEBUG|------>[#hitcriteria:Proactively schedule a branch visit]
 
String tmpBody = 'TestBamo[#taskdate:2016-11-15 00:00:00][#hitcriteria:Proactively schedule a branch visit]';
String[] bodyList = tmpBody.split('\\['); 
list<string> finalBodyList = new list<string>();

for(integer i=0; i < bodyList.size(); i++){
    if(i == 0)  finalBodyList.add(bodyList.get(i));//Don't add [ to first element 
    else  finalBodyList.add('['+bodyList.get(i));//Add missing [ to rest of strings   
}
for(String s : finalBodyList){
 system.debug('------>'+s);
}

If this is enough(without starting [ ), try below code
|DEBUG|------>TestBamo
|DEBUG|------>#taskdate:2016-11-15 00:00:00]
|DEBUG|------>#hitcriteria:Proactively schedule a branch visit]
 
String tmpBody = 'TestBamo[#taskdate:2016-11-15 00:00:00][#hitcriteria:Proactively schedule a branch visit]';
String[] bodyList = tmpBody.split('\\['); 
for(String s : bodyList){
    system.debug('------>'+s); 
}

Please let me know if it helps.

Thanks,
Nagendra Prasad