我有一部分String 数据格式是这样的
{value=加大 +$5},{value=加加大 +$10},{value=加加加大 +$15}
我想把
加大、加加大、加加加大 存进去 Arraylist name.
$5、$10、$15 存进去 Arraylist price.
请教大神们如何实现这种数据转型?
代言2016-11-09 15:46:55
public class test { public static void main(String[] args) { String str = "{value=加大 +$5},{value=加加大 +$10},{value=加加加大 +$15}"; test(str); } public static void test(String str) { Listname = new ArrayList<>(); List price = new ArrayList<>(); String[] data = str.split(","); for (int i = 0; i < data.length; i++) { String temp = data[i]; temp = temp.substring(1, temp.length() - 1); temp = temp.substring(temp.indexOf("value=") + "value=".length()); String[] subs = temp.split("\\+"); name.add(subs[0]); price.add(subs[1]); } System.out.println("name: " + name); System.out.println("price: " + price); } } 输出: name: [加大 , 加加大 , 加加加大 ] price: [$5, $10, $15]
三叔2016-11-09 15:46:40
可以用正则表达式
class Untitled { public static void main(String[] args) { String target = "{value=加大 +$5},{value=加加大 +$10},{value=加加加大 +$15}"; String valueRegex = "[\\u4e00-\\u9fa5]+";//匹配汉字 String numberRegex = "\\$\\d+";//匹配"$数字" Pattern pattern = Pattern.compile(valueRegex); Matcher m = pattern.matcher(target); ListvalueResult = new ArrayList<>(); while(m.find()){ valueResult.add(m.group()); } pattern = Pattern.compile(numberRegex); m = pattern.matcher(target); List numberResult = new ArrayList<>(); while(m.find()){ numberResult.add(m.group()); } System.out.println(valueResult); System.out.println(numberResult); } }
输出结果
[加大, 加加大, 加加加大] [$5, $10, $15]