这是一个解析方法,用以解析由().and.or组成的表达式, (你也可以自己添加规则)
如果想用数学上的带有()组合的表达式一样来处理与或操作
那么这个方法完全适合. _
例如你需要对以下规则进行数据过滤:
(region = “asia”) AND ((status = null) OR ((inactive = “true”) AND (department = “aaaa”)) OR ((costcenter = “ggg”) OR (location = “india”)))
处理流程介绍
现在有一批学生数据, 我想要筛选其中的女学生, 并且成绩都及格的, 或者是喜欢篮球的男生, 那么我们规定的规则如下:
((student.sex=0) and (student.score > 60) ) or ((student.sex=1) and (student.hobbies='basketball'))
- 解析后的单条规则:
@1: student.sex=0
@2: student.score > 60
@3: @1 and @2
@4: student.sex=1
@5: student.hobbies=‘basketball’
@6: @4 and @5
@7: @3 or @6 - 根据每个单规则, 生成规则函数, 例如
Predicate<Student> =
student -> {
if (student.sex==0) {
return true;
}else{
return false;
}
};
- 将规则函数整合为最终的规则, 最终只会有一个规则函数
例如and符
// and规则函数集合
List<Predicate<Student>> mappers;
// 合并后的规则函数
Predicate<Student> =
student -> mappers.stream()
.reduce(t ->true, Predicate::and)
.test(student);
- 对数据进行过滤
规则解析器
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 这是一个解析方法,用以解析由().and.or组成的表达式
* 如果想用数学上的带有()组合的表达式一样来处理与或操作
* 那么这个方法完全适合. ~_~
*
* this is a common function of parsing str expression which combined by (). and . or .,
* if you want to operate the str like a mathematical expression,
* this is method is nice for you
*
* @author lycaon
* @date 05-29
* @version 1.0.0
*/
public class FilterCommandParser {
private static final Pattern BRACED_REDUX = Pattern.compile("\\(([^()]*)\\)");
/**
* <pre>
* String exp = "(region = "asia") AND ((status = null) OR ((inactive = "true") AND (department = "aaaa")) OR ((costcenter = "ggg") OR (location = "india")))";
* List<String> decodedExp = parse(exp);
* for (int i = 0; i < decodedExp.size(); ++i) {
* System.out.println("@%d = %s%n", i, decodedExp.get(i));
* }
* decodeExp:
* @0 = region = "asia"
* @1 = status = null
* @2 = inactive = "true"
* @3 = department = "aaaa"
* @4 = @2 AND @3
* @5 = costcenter = "g