Java - 查看输入是否仅包含运算符左侧的数字

Java - see if input contains only numbers to the left of the operator

我有一个似乎无法解决的问题。 当输入仅在运算符的左侧有数字时,我只想要一段代码 运行 。 例如: 如果输入是 100+,那么代码应该 运行.

而且如果输入是 100-、100*、100/、100^ 等

我也希望能够解析像 -100*50 这样的表达式。

如果问题不清楚,我很抱歉。

此方法使用 Regular Expression 匹配以可选 - 符号开头的行,可选 space,然后是一个或多个数字,可选 space,一个运算符(在本例中,+-*/^)m 一个可选的 space,一个可选的- 符号,一个可选的 space,然后是一个或多个数字,最后是可选的行结尾。

public static void main(String[] args)
{
    Pattern p = Pattern.compile("^\-?\s?\d+\s?[\+\-*\/\^]\s?\-?\s?\d+\r?\n?$");
    System.out.println(p.matcher("123+").matches()); // outputs "true"
    System.out.println(p.matcher("123").matches()); // outputs "false"
    System.out.println(p.matcher("- 123123 *").matches()); // outputs "true"
    System.out.println(p.matcher("- 9843 * 23409").matches()); // outputs "true"
}

您也可以 try it online 并提供您自己的意见。

我认为使用正则表达式最适合您的情况。你可以这样写:

    String input = "100a^atcs";
    Pattern p = Pattern.compile("(\d+[\+\-\*\^].*)");
    Matcher m = p.matcher(input);
    if (m.matches())
    {
        //do code...
    }