简体   繁体   English

如何处理字符串以获取布尔输出

[英]how to process the string to get a boolean output

I have a string like 我有一个像

String str="(0 & (0 || 1))";

I want to process this as boolean output.For example 我想将此作为布尔输出处理。例如

(0||1)= 1
(0 & 1)=0

so my final output should be 0 as per the string "(0 & (0 || 1))"; 所以我的最终输出应是0为每串"(0 & (0 || 1))";

How do you process this? 您如何处理呢?

I tried with the below code: 我尝试了以下代码:

String str="(1 & (1 & 1))";

    str=str.replaceAll("1","true");

    str=str.replaceAll("0", "false");

    System.out.println(str);

    Boolean boolean2 = Boolean.parseBoolean(str);

    String sr=String.valueOf(str);

    System.out.println(boolean2);

Java does not have an eval() statement that can take a string of code and compile and interpret it within a program. Java没有eval()语句,该语句可以接受代码字符串程序中进行编译和解释。 You could, using Java, write such a command (you have access to the java parser, can write your own classloader, ...), but why bother whenyou already have built-in scripting support in the language. 您可以使用Java编写这样的命令(您可以访问Java解析器,可以编写自己的类加载器,...),但是当您已经拥有该语言的内置脚本支持时,何必麻烦呢。

The usual way to interpret expressions is to write a parser for your expression language and interpret the resulting parse tree (if you do not understand words like "parser" and "parse tree" this is not the easiest route for you). 解释表达式的通常方法是为表达式语言编写一个解析器并解释生成的解析树(如果您不理解“ parser”和“ parse tree”之类的单词,这对您来说不是最简单的方法)。 When done correctly, this is the fastest approach. 如果正确完成,这是最快的方法。

However, you can also rely on the built-in scripting support: 但是,您也可以依赖内置的脚本支持:

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class T {

    public static String interpret(String js) {
        try {
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
            return engine.eval(js).toString();
        } catch (ScriptException e) {
            // Shouldn't happen unless somebody breaks the script
            throw new RuntimeException(e);
        }
    }

    public static void main(String args[]) {
        String str=args[0];
        str = str.replaceAll("1", "true");
        str = str.replaceAll("0", "false");
        str = str.replaceAll(" [&] ", "&&");
        str = str.replaceAll(" [|] ", "||");        
        System.out.println(interpret(str));
    }
}

Notice that this is somewhat slow and generally considered cheating if the exercise expected you to use a parser. 注意,这有点慢,如果练习希望您使用解析器,通常会认为是作弊。 Additionally, since JS is a full-fledged language, it is a lot less safe than having a custom-built, restricted parser: you have to go to great lengths to sanitize the JS to prevent people from entering "evil expressions" that can tie up your system or do other nasty stuff. 此外,由于JS是一种成熟的语言,因此它比拥有定制的受限解析器要安全得多:您必须花大力气来清理JS,以防止人们输入可能与之相关的“邪恶表达”升级系统或执行其他令人讨厌的事情。

The output is, for 输出为

javac T.java && java T "(0 & (0 || 1))"

(notice that the first argument to the program is the expression to parse) (请注意,程序的第一个参数是要解析的表达式)

false

Well, basically there are 2 ways that comes to my mind to solve this issue: 好吧,基本上我可以通过两种方法解决此问题:

  1. Create a custom parser for your expressions. 为您的表达式创建一个自定义解析器。 Things like ANTLR or JavaCC may help you, but you can even create your own lexer/parser, there are tons of docs and books about that - but it's not that trivial. 诸如ANTLRJavaCC之类的东西可能会为您提供帮助,但是您甚至可以创建自己的词法分析器/解析器,有关此的大量文档和书籍-但这并不琐碎。
  2. A bit easier is to call an engine that can evaluate that expression for you. 调用一个可以为您评估该表达式的引擎要容易一些。 Here's an example how to do it in JavaScript, which is within your JDK by default: 这是一个示例,该示例说明了如何使用JavaScript(默认情况下位于JDK内)执行此操作:

     String str = "(true && (false || true))"; ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript"); System.out.println(engine.eval(str)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM