kknaguib
kknaguib

Reputation: 749

Splitting string by square brackets

I have a string that comes out like this: 1.[Aagaard,Lindsay][SeniorPolicyAdvisor][TREASURYBOARDSECRETARIAT][DEPUTYPREMIERANDPRESIDENTOFTHETREASURYBOARD,Toronto][416-327-0948][[email protected]]2.[Aalto,Margaret][ProbationOfficer][CHILDRENANDYOUTHSERVICES][THUNDERBAY,ThunderBay][807-475-1310][[email protected]]

I want to split it into an arraylist like this:

1.

Aagaard,Lindsay

SeniorPolicyAdvisor

etc.

Any suggestions?

Upvotes: 0

Views: 4030

Answers (3)

Maljam
Maljam

Reputation: 6284

Simply this:

String[] list = str.split("\\[");

for(int i = 0 ; i < list.length ; i++) {
    list[i] = list[i].replace("\\]", "");
}

Upvotes: 0

Daniel Mart&#237;n
Daniel Mart&#237;n

Reputation: 117

First delete the first and the last brackets and then split by '][':

String arr = "[Aalto,Margaret][ProbationOfficer][CHILDRENANDYOUTHSERVICES]";
String[] items = arr.substring(1, arr.length() - 1).split("][");

Upvotes: 1

kknaguib
kknaguib

Reputation: 749

I read the JavaDoc and used Pattern and Matcher like so:

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher m = p.matcher(tableContent);

while(m.find()) {
  System.out.println(m.group(1));
}

Upvotes: 3

Related Questions