假设你有一行 String condition = "A or B and C"; 语句,请问怎么做才能变成一行真正的逻辑表达式(能在计算机中运行计算)?
Resolution
- 声明一个
List<List<String>>结构; - 先分割 or ;
变成 [ A, B and C ] - 不包含and的,插入
List<List<String>>结构;
List<List<String>>.add( [A] ) - 声明一个
List<String>, 再分割 and;
List<String>.add(B);
List<String>.add(C); - 把④加入
List<List<String>>结构,
List<List<String>>.add( [B, C]); - 最终
List<List<String>>结构如下:
[ [A], [B,C] ] - 这个
List<List<String>>结构里面的条件语句就是任意一行必须为真语句,简而言之:判断A是不是为真,A为真则整个结构都为真, 或者判断[B, C]是否都为真,如果都为真则整个结构都为真。以此类推。 
Example 2
如果是从文本里一行一行的读取用户的自定义配置,并且每行后面是一些特殊的Payload,就有可能会混着OR 、AND 语句,那就不适合使用上面的分割法,容易将Payload也分割了。
NO, IamSentence A
OR, IamSentence B
AN, IamSentence C
先固定Text的逻辑关键词的长度,NO表示第一行,OR=or, AN=and。
思路就是:
- 先将所有语句都并列成一句来分析,
NO A OR B AN C=A OR (B AN C),就能看出整体性的逻辑; - 循环所有语句;
 - 先将第一行的NO 语句存储起来;
 - Next 无非就是 
AN或OR两种情况,针对这两个条件分别做不同的处理即可; 
Java代码实现该算法:
   public static void main(String[] args) {
        List<String> rawSentence = new ArrayList<String>();
        rawSentence.add("NO, IamSentence A");
        rawSentence.add("OR, IamSentence B");
        rawSentence.add("AN, IamSentence C");
        parseAnOr(rawSentence);
    }
    public static List<List<String>> parseAnOr(List<String> rawSentence) {
        List<List<String>> allList = new ArrayList<>();
        String temp = "";
        String last = "";
        ArrayList<String> tempList = new ArrayList<String>();
        for (int i = 0; i < rawSentence.size(); i++) {
            if (rawSentence.get(i).substring(0, 2).equals("NO")) {
                last = rawSentence.get(i).substring(3);
                last = last.trim();
            }
            if (rawSentence.get(i).substring(0, 2).equals("OR")) {
                if (!last.equals("")) {
                    tempList.add(last);
                    last = "";
                    allList.add(new ArrayList<>(tempList));
                    tempList.clear();
                }
                if (tempList.size() > 0) {
                    allList.add(new ArrayList<>(tempList));
                    tempList.clear();
                }
                //
                last = rawSentence.get(i).substring(3);
                last = last.trim();
                tempList.clear();
            }
            if (rawSentence.get(i).substring(0, 2).equals("AN")) {
                tempList.add(last);
                last = "";
                last = rawSentence.get(i).substring(3);
                last = last.trim();
            }
        }
        if (!last.equals("")) {
            tempList.add(last);
            allList.add(new ArrayList<>(tempList));
        }
        System.out.println(allList);
        return allList;
    }
out
[[IamSentence A], [IamSentence B, IamSentence C]]
Practice
If it were A or B and C and D or E, what would you do?
                    
                
                
            
        
浙公网安备 33010602011771号