Reputation: 111
I am trying to change a list string to list, there is the string:
var liststr = "[['one', 'two', 'three', 'four'], ['one\'s next', 'two\'s next', 'three\'s next', 'four\'s next']]";
I tried json.decode, but report error because single quotes, I don't know other ways to solve this problem.
so I want to ask how to solve it in dart, thank you~
Upvotes: 1
Views: 475
Reputation: 27137
Check Out following way to convert string list into list of string.
1) This joints all the elements in one list.
var list =
"[['one', 'two', 'three', 'four'], ['one\'s next', 'two\'s next', 'three\'s next', 'four\'s next']]";
final regExp =
new RegExp(r"(\w+\\?\'?\w*\s?\w+)");
var result = regExp
.allMatches(list)
.map((m) => m.group(1))
.map((String item) => item.replaceAll(new RegExp(r'[\[\],]'), ''))
.map((m) => m)
.toList();
print(result);
Output: [one, two, three, four, one, s, next, two, s, next, three, s, next, four, s, next]
2) If You want it list item wise then follow below code.
var list =
"[['one', 'two', 'three', 'four'], ['one\'s next', 'two\'s next', 'three\'s next', 'four\'s next']]";
final regExp = new RegExp(r'(?:\[)?(\[[^\]]*?\](?:,?))(?:\])?');
final regExp2 = new RegExp(r"(\w+\\?\'?\w*\s?\w+)");
final result = regExp
.allMatches(list)
.map((m) => m.group(1))
.map((String item) => item.replaceAll(new RegExp(r'[\[\],]'), ''))
.map((m) => [m])
.toList();
final result2 = List();
for (int i = 0; i < result.length; i++) {
result2.add(regExp2
.allMatches(result[i].toString())
.map((m) => m.group(1))
.map((m) => m)
.toList());
}
print(result2[0]);
print(result2[0][0]);
output: [one, two, three, four]
one
Upvotes: 1