Java - 如何验证以下输入格式 'operand operator operand'(例如 1.4 * 5)

Java - how to validate following input format 'operand operator operand' (e.g. 1.4 * 5)

我正在绞尽脑汁想弄清楚我的代码中有什么问题。 我要求用户插入以下格式:

LeftOperand operator RightOperand

其中:

我搜索并发现了几个正则表达式,但它们似乎都不适合我,除了以下内容之外的任何内容:3 +/-/*// 5 return 是一个错误。 应该有效:

但实际上只有那些有效,而其余的 return 错误:

我目前在我的代码中使用以下正则表达式:

"[((\d+\.?\d*)|(\.\d+))] [+,\-,*,/] [((\d+\.?\d*)|(\.\d+))]"

尝试了所有类型的正则表达式,但 none 似乎有效,我只是不知道我做错了什么:

[[+-]?([0-9]*[.])?[0-9]] [+,\-,*,/] [[+-]?([0-9]*[.])?[0-9]]

这是我的客户端代码:

private static final int SERVER_PORT = 8080;
private static final String SERVER_IP = "localhost";
private static final Scanner sc = new Scanner(System.in);
private static final String regex = "[((\d+\.?\d*)|(\.\d+))] [+,\-,*,/] [((\d+\.?\d*)|(\.\d+))]";

public static void main(String[] args) throws IOException {
    // Step 1: Open the socket connection
    Socket serverSocket = new Socket(SERVER_IP, SERVER_PORT);

    // Step 2: Communication-get the input and output stream
    DataInputStream dis = new DataInputStream(serverSocket.getInputStream());
    DataOutputStream dos = new DataOutputStream(serverSocket.getOutputStream());

    //Run until Client decide to disconnect using the exit phrase
    while (true) {
        // Step 3: Enter the equation in the form -
        // "operand1 operation operand2"
        System.out.print("Enter the equation in the form: ");
        System.out.println("'operand operator operand'");

        String input = sc.nextLine();
        // Step 4: Checking the condition to stop the client
        if (input.equals("exit"))
            break;

        //Step 4: Check the validity of the input and
        // return error message when needed
        if (input.matches(regex)) {
            System.out.println("Expression is correct: " + input);
        } else {
            System.out.println("Expression is incorrect, please try again: ");
            continue;
        }

        // Step 5: send the equation to server
        dos.writeUTF(input);

        // Step 6: wait till request is processed and sent back to client
        String ans = dis.readUTF();
        // Step 7: print the response to the console
        System.out.println("Answer=" + Double.parseDouble(ans));
    }
}
private static final String NUM = "(-?\d+(\.\d*)?)";
private static final String OP = "([-+*/])"; // Minus at begin to avoid confusion with range like a-z.
private static final String WHITESPACE = "\s*";
private static final String regex = NUM + WHITESPACE + OP + WHITESPACE + NUM;

注:

  • </code>对应第一个数字</li> <li><code>对应运算符
  • </code>对应第二个数</li> <li><code>(...) 是一个 ($1, $2, ...; $0 是全部)
  • [...]是一个字符集,一个字符匹配
  • X? X 可选
  • X* X 0 次或更多次
  • X+ X 1 次或更多次
  • \s space, 选项卡
  • \d位数