0

我正在努力弄清楚我的代码有什么问题。我要求用户插入以下格式:

LeftOperand operator RightOperand

在哪里:

  • LeftOperand - 可以是任何整数或浮点数
  • 运算符 - 可以是 +、-、* 或 /
  • RightOperand - 可以是任何整数或浮点数

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

  • 1 + 3
  • 1 / 4
  • 1.3 - 4
  • 4 - 5.3
  • 123 * 3434
  • 12.34 * 485

但实际上只有那些是有效的,而其余的则返回错误:

  • 1 + 3 - 正确
  • 1 / 4 - 正确
  • 1.3 - 4 - 错误
  • 4 - 5.3 - 错误
  • 123 * 3434 - 错误
  • 12.34 * 485 - 错误

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

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

尝试了各种正则表达式,但似乎都不起作用,我只是不知道我做错了什么:

[[+-]?([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));
    }
}
4

1 回答 1

1
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;

笔记:

  • $1对应第一个数字
  • $3与运营商对应
  • $4对应第二个数字
  • (...)是一个($1, $2, ...; $0 是全部)
  • [...]是一个字符集,一个字符匹配
  • X?X 可选
  • X*X 0 次或多次
  • X+X 1 次或更多次
  • \\s空格,制表符
  • \\d数字
于 2021-11-27T16:42:36.077 回答