2

I have some sampel data written on a file. The data are in the following format -

[Peter Jackson] [UK] [United Kingdom] [London]....

I have to extract the information delimited by '[' and ']'. So that I found -

Peter Jackson  
UK  
United Kingdom  
London  
...
...

I am not so well known with string splitting. I only know how to split string when they are only separated by a single character (eg - string1-string2-string3-....).

Cœur
  • 37,241
  • 25
  • 195
  • 267
pksaha
  • 59
  • 6

5 Answers5

2

You can use this regex:

\\[(.+?)\\]

And the captured group will have your content.

Sorry for not adding the code. I don't know java

Amit Joki
  • 58,320
  • 7
  • 77
  • 95
2

You should use regex for this.

Pattern p = Pattern.compile("\\[(.*?)\\]");
Matcher results = p.matcher("[Peter Jackson] [UK] [United Kingdom] [London]....");

while (results.find()) {
    System.out.println(results.group(1));
}
wns349
  • 1,266
  • 1
  • 10
  • 20
2

Is each item separated by spaces? if so, you could split by "\] \[" then replace all the left over brackets:

    String vals = "[Peter Jackson] [UK] [United Kingdom] [London]";
    String[] list = vals.split("\\] \\[");
    for(String str : list){
        str = str.replaceAll("\\[", "").replaceAll("\\]", "");
        System.out.println(str); 
    }

Or if you want to avoid a loop you could use a substring to remove the beginning and ending brackets then just separate by "\\] \\[" :

    String vals = " [Peter Jackson] [UK] [United Kingdom] [London] ";
    vals = vals.trim(); //removes beginning whitspace
    vals = vals.substring(1,vals.length()-1); // removes beginning and ending bracket
    String[] list = vals.split("\\] \\[");
Bryan
  • 1,938
  • 13
  • 12
1

Try to replace

    String str = "[Peter Jackson] [UK] [United Kingdom] [London]";
    str = str.replace("[", "");
    str = str.replace("]", "");

And then you can try to split it.

eliasah
  • 39,588
  • 11
  • 124
  • 154
1

Splitting on "] [" should sort you, as in:

\] \[

Regular expression visualization

Debuggex Demo

After this, just replace the '[' and the ']' and join using newline.

hd1
  • 33,938
  • 5
  • 80
  • 91