我在绞尽脑汁想弄清楚我的代码出了什么问题。我要求用户插入以下格式:
LeftOperand operator RightOperand其中:
可以是任意int或number
。
我搜索并找到了很少的正则表达式,但它们似乎都不适合我,因为除了以下内容:3 +/-/*// 5返回一个错误。应有效:
H 119123*3434H 220H 12112.34*485H 222f 223
但实际上,只有这些内容是有效的,而其余的返回错误:
<代码>H 133123* 3434 -错误<代码>H 234<代码>H 13512.34* 485 -错误<代码>H 236<代码>F 237
我目前正在代码中使用以下regex:
"[((\\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));
}
}发布于 2021-11-27 16:42:36
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对应于第一个number$3对应于第二个number(...)对应的是一个组($1,$2,.;$0是all)[...]是一个字符集,一个字符matchX? X optionalX* X0或更多timesX+ X1或更多times\\s空间,tab\\d数字https://stackoverflow.com/questions/70136606
复制相似问题