Reputation: 111
I have a problem with String substring option. I wanted to add some parts from a String into an ArrayList, but I only get to add the first text.
ArrayList<String> arr = new ArrayList<String>();
String text = "[\"text1\",\"text2\",\"text3\"]";
text = text.substring(text.indexOf("\"") + 1);
text = text.substring(0, text.indexOf("\""));
arr.add(text);
for (int i = 0; i < arr.size(); i++) {
System.out.println(arr.get(i));
}
The output for this is:
text1
I would like the add all "texts" in the Array, each one in a different position:
text1
text2
text3
Is there any possibility to do this? Thanks in advance.
Upvotes: 2
Views: 1361
Reputation: 61198
You can using split
fairly easily:
public static void main(final String[] args) throws Exception {
final String input = "[\"text1\",\"text2\",\"text3\"]";
final List<String> output = new ArrayList<>();
for(final String item : input.replaceAll("^\\[\"|\"\\]$", "").split("\",\"")) {
output.add(item);
}
for(final String item : output) {
System.out.println(item);
}
}
Output:
text1
text2
text3
The String
you are trying to parse looks amazingly like the output of Collection.toString
, if that's the case then this is all wrong...
Upvotes: 1
Reputation: 12040
String#split
using the regex and don't add the first and last element in the array to the arraylist.
String str[]=text.split("\"(,)?");
ArrayList<String> arr=new ArrayList<String>();
for(int i=1;i<str.length-1;i++){
System.out.print(str[i]+"\n");
arr.add(str[i]);
}
OUTPUT:
text1
text2
text3
Upvotes: 1
Reputation: 53565
Run:
String text = "[\"text1\",\"text2\",\"text3\"]";
Pattern p = Pattern.compile("\"(.*?)\"");
Matcher m = p.matcher(text);
while (m.find()) {
System.out.println(m.group());
}
OUTPUT:
"text1"
"text2"
"text3"
Upvotes: 2
Reputation: 11483
How about a regex pattern?:
String text = "[\"text1\",\"text2\",\"text3\"]";
String[] split = text.split("\"(,)?");
Upvotes: 0