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));
}
Question
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-....).
Solution
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));
}
OTHER TIPS
You can use this regex:
\\[(.+?)\\]
And the captured group will have your content.
Sorry for not adding the code. I don't know java
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("\\] \\[");
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.
Splitting on "] [" should sort you, as in:
\] \[
After this, just replace the '[' and the ']' and join using newline.