我想eval()
以下文字:
(2, [(3, 4), (5, 6)])
在Java中,对于我定义的一些对象,我们假设:
new Pair(1, new ArrayList<Pair>({new Pair(3,4), new Pair(5,6)}))
实现这一目标的策略是什么?我的想法是,我可以得到以下任何一个:
(2, [(3, 4), (5, 6), (5, 6)])
(2, [(3, 4), (5, 6)])
(2, [(3, 4)])
我应该将它与正则表达式匹配吗?
这是我的尝试:
/\(([0-9]+), \[(?:\(([0-9]+), ([0-9]+)\)(?:, )?)+\]\)/
答案 0 :(得分:1)
这样的事情可能就是你想要的。抱歉,格式化方面还有点新鲜。
import javafx.util.Pair;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String test[] = {"(2, [(3, 4), (5, 6), (5, 6)])",
"(7, [(3, 4), (5, 6)])",
"(10, [(3, 4)])"
};
// clean string
for (int i = 0; i < test.length; i++){
test[i] = test[i].replace("(", "")
.replace("[", "")
.replace(")", "")
.replace("]", "")
.replace(" ", "");
}
List<Pair> pairList = new ArrayList();
for (String s : test){
String[] tmpStrArr = s.split(",");
List<Pair> tmpLst = new ArrayList<Pair>();
int index = Integer.parseInt(tmpStrArr[0]);
for (int i = 1; i < tmpStrArr.length; i += 2){
tmpLst.add(new Pair(index, new Pair(tmpStrArr[i], tmpStrArr[i + 1])));
}
pairList.addAll(tmpLst);
}
// just here for break point
System.out.println();
}