1"),解析表达式并返回布尔值" /> 1"),解析表达式并返回布尔值 - 且购网" />

且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何解析输入字符串(例如"4> 1"),解析表达式并返回布尔值

更新时间:2023-02-10 21:02:31

没有简单的答案

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

Boolean.valueOf(String)方法的目标不是评估条件或方程式.将值"true""false"String转换为Boolean对象是一种简单的方法.

The goal of the Boolean.valueOf(String) method is not to evaluate conditions or equations. It is just a simple method to convert a String with value "true" or "false" to a Boolean object.

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

Anyway, if you want this kind of functionality, you have to set some clear limitations. (note: some equations have no answer: "0/0 = 0/0")

如果您只是将整数与整数进行比较,则可以假定方程式始终采用以下格式:

If you are simply comparing integers with integers, then you could assume that the equations will always be in the following format:

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

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

Then, what you could do, is split your string in 3 parts using a regular expression.

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 等).这些引擎可以调用javascript方法,例如 eval(...) javascript方法,正是您需要的.因此,这可能是一个更好的解决方案.

Script Engines

Java also supports script engines (e.g. Nashorn and others). These engines can call javascript methods, such as the eval(...) javascript method, which is exactly what you need. So, this is probably a better solution.

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)".

This solution can handle more complicated input, such as "!(4>=10)".

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