[英]Java regex for numeric input with '-' char in the beginning is acceptable
I need to support inputs of int numbers like "100", double like "150.84", but also be able to accept an input like this "-458.2" or "-450". 我需要支持int数的输入,例如“ 100”,也可以支持双精度的数字,例如“ 150.84”,但还需要接受诸如“ -458.2”或“ -450”的输入。
For the int/double part I use : input.matches("\\\\d+\\\\.\\\\d+")) || input.matches("\\\\d+"))
对于int / double部分,我使用:
input.matches("\\\\d+\\\\.\\\\d+")) || input.matches("\\\\d+"))
input.matches("\\\\d+\\\\.\\\\d+")) || input.matches("\\\\d+"))
But how can make it acceptable to have the minus character at the beginning? 但是如何使开头具有减号成为可以接受的呢?
You can allow an optional -
like this: 您可以允许一个可选的
-
像这样:
input.matches("-?\\d+\\.\\d+"))
You can also write it in one Regex: 您也可以在一个Regex中编写它:
input.matches("-?\\d+(?:\\.\\d+)?"))
?:
declares a non-capturing group since you don't want to extract this part ?:
声明一个非捕获组,因为您不想提取这部分
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.