0%

高级筛选

高级筛选

Java解析运算表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
        //高级筛选 option1、option2、option3、option4为筛选条件
String input = "((option1&&option2)||(option3&&option4))";
//用正则表达式去掉逻辑运算符
String optionStr = input.replaceAll("[\\(\\)]", "").replaceAll("\\&&", ",").replaceAll("\\|\\|", ",");
System.out.println("option String: " + optionStr);
List<String> optionList = Arrays.asList(optionStr.split(","));
//条件最大值
int maxOption = 0;
for (String option : optionList) {
int optionNum = Integer.parseInt(option.replace("option", ""));
if (optionNum > maxOption) {
maxOption = optionNum;
}
}
System.out.println("option maxNum: " + maxOption);
System.out.println("option List: " + JSON.toJSONString(optionList));
//执行各个条件查询,将结果放到map中,key为条件条件,value为结果集合
int size = optionList.size();
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < size; i++) {
List<String> list = new ArrayList<>();
for (int j = 0; j <= i; j++) {
list.add("empi-" + (j + 1));
}
map.put(optionList.get(i), list);
}
System.out.println("option and result map: " + JSON.toJSONString(map));

/**
* 正则表达式匹配,求出最小运算单元结果集,并替换
* ((option1&&option2)||(option3&&option4))
* -->(option5||(option3&&option4))
* -->(option5||option6)
* -->option7 最终结果
*/
Pattern r = Pattern.compile("\\(option[0-9]&&option[0-9]\\)|\\(option[0-9]\\|\\|option[0-9]\\)");
Pattern r1 = Pattern.compile("option[0-9]");
Matcher m = r.matcher(input);

while (m.find()) {
String temp = m.group();
System.out.println(temp);
Matcher m1 = r1.matcher(temp);
m1.find();
String option1 = m1.group();
m1.find();
String option2 = m1.group();
System.out.println(option1 + "--" + option2);
maxOption++;

List list1 = map.get(option1);
List list2 = map.get(option2);
if (temp.contains("&&")) {
list1.retainAll(list2);
} else {
list1.removeAll(list2);
list1.addAll(list2);
}
map.put("option" + maxOption, list1);
input = input.replace(temp, "option" + maxOption);
System.out.println("input: " + input);
m = r.matcher(input);
}
System.out.println("option and result map: " + JSON.toJSONString(map));