如何解析输入字符串,例如“4>1”,解析表达式和 return 布尔值

how to parse an input string such as "4>1", resolve the expression and return boolean

我正在学习 Java,不知道如何将输入字符串(例如 "4>1")转换为布尔值 return。

我想要实现的目标是,让 Java return boolean(true/false) 基于用户输入,在 String?

例如,我尝试为输入“!(4>=10)”获取“true”的 return 值。

没有简单的答案

对于初学者来说,没有简单的解决方案。我注意到有人提到 Boolean.valueOf(...);

Boolean.valueOf(String) 方法的目标不是评估条件或方程。这只是一个简单的方法,可以将值 "true""false"String 转换为 Boolean 对象。

无论如何,如果你想要这种功能,你必须设置一些明确的限制。 (注意:有些方程没有答案:“0/0 = 0/0”)

正则表达式解析

如果您只是简单地将整数与整数进行比较,那么您可以假设方程式将始终采用以下格式:

<integer1>[whitespace]<operator>[whitespace]<integer2>

然后,您可以使用正则表达式将字符串分成 3 部分。

public static boolean evaluate(String input)
{
  Pattern compile = Pattern.compile("(\d+)\s*([<>=]+)\s*(\d+)");
  Matcher matcher = compile.matcher(input);
  if (matcher.matches())
  {
    String leftPart = matcher.group(1);
    String operatorPart = matcher.group(2);
    String rightPart = matcher.group(3);

    int i1 = Integer.parseInt(leftPart);
    int i2 = Integer.parseInt(rightPart);

    if (operatorPart.equals("<")) return i1 < i2;
    if (operatorPart.equals(">")) return i1 > i2;
    if (operatorPart.equals("=")) return i1 == i2;
    if (operatorPart.equals("<=")) return i1 <= i2;
    if (operatorPart.equals(">=")) return i1 >= i2;

    throw new IllegalArgumentException("invalid operator '" + operatorPart + "'");
  }

  throw new IllegalArgumentException("invalid format");
}

脚本引擎

Java 还支持脚本引擎(例如 Nashorn and others). These engines can call javascript methods, such as the eval(...) javascript 方法,这正是您所需要的。所以,这可能是一个更好的解决方案。

public static boolean evaluate(String input)
{
  try
  {
    ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
    Object result = engine.eval("eval('" + input + "');");
    return Boolean.TRUE.equals(result);
  }
  catch (ScriptException e)
  {
    throw new IllegalArgumentException("invalid format");
  }
}

这个解决方案可以处理更复杂的输入,例如"!(4>=10)"

注意:出于安全原因,您可能希望从用户输入中去除特定字符。 (例如 ' 字符)