How to parse OR AND within text

发布时间 2023-09-14 17:20:15作者: Mysticbinary

假设你有一行 String condition = "A or B and C"; 语句,请问怎么做才能变成一行真正的逻辑表达式(能在计算机中运行计算)?

Resolution

  1. 声明一个List<List<String>>结构;
  2. 先分割 or ;
    变成 [ A, B and C ]
  3. 不包含and的,插入List<List<String>>结构;
    List<List<String>> .add( [A] )
  4. 声明一个List<String>, 再分割 and;
    List<String>.add(B);
    List<String>.add(C);
  5. 把④加入List<List<String>>结构,
    List<List<String>>.add( [B, C]);
  6. 最终List<List<String>>结构如下:
    [ [A], [B,C] ]
  7. 这个List<List<String>>结构里面的条件语句就是任意一行必须为真语句,简而言之:判断A是不是为真,A为真则整个结构都为真, 或者判断[B, C]是否都为真,如果都为真则整个结构都为真。以此类推。

Practice

If it were A or B and C and D or E, what would you do?