I want to convert this String:
String s = "[\"val1\", \"val2\", \"val3\"]";
to an array or an ArrayList (without regex and split). It's from a Database, and it's generic. It's also possible to have commas inside the high quotes.
Is this possible?
Unfortunately, there is no java API that would directly parse this list.
This snippet would work for this String:
String s = "[\"val1\", \"val2\", \"val3\"]";
String[] arr = s.replace("[", "").replace("]", "").split("\\s*,\\s*");
List<String> list = Arrays.asList(arr);
If the string contains [
or ]
somewhere else, then the snippet above won't work.
I suggest to figure out what is this. Is this a JSON array? Then use a JSON parser. Is this a csv with additional [
and ]
? Then use a CSV parser.
String json = "[\"val1\", \"val2\", \"val3\"]";
JSONArray jsonarray = new JSONArray(json);
List<Object> objects = jsonarray.toList();
Thanks to @TamasRev
Yes, there is a way using Regex.
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class T1 {
public static void main(String[] args) {
final String REGEX = "\\b([\\w]+)\\b";
String INPUT = "[\"val1\", \"val2\", \"val3\"]";
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // get a matcher object
List<String> myList = new ArrayList<>();
while(m.find()) {
myList.add(m.group());
}
System.out.println(myList);
}
}
You can use a String tokenizer and set as delimiters " \\",[]"
. This is my example. I've used an array, but it's very simple to convert it in a ArrayList if you want.
public static void main(String[] args) {
String s = "[\"val1\", \"val2\", \"val3\"]";
String delims = " \",[]";
StringTokenizer st = new StringTokenizer(s, delims);
System.out.println("Num of Token = " + st.countTokens());
String[] myArr= new String[st.countTokens()];
for(int i=0; i<myArr.length && st.hasMoreTokens(); i++)
myArr[i]=st.nextToken();
//output
System.out.println(Arrays.toString(myArr));
}
Your output will be:
Num of Token = 3
[val1, val2, val3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.