gpt4 book ai didi

java - 如何检查任何输入的字符串是否采用任何特定格式(###.#)

转载 作者:行者123 更新时间:2023-11-30 06:21:24 25 4
gpt4 key购买 nike

我想检查用户输入的字符串是否仅采用这种格式-

我当前的代码处理所有格式:##.#, ###.#, ###, ##

但它无法检测用户何时键入 #########

 // check if format: ###.# for weight and AAAA for name
if (weight.matches("\\d{3}.\\d{1}")) {
} else if (weight.matches("\\d{2}.\\d{1}")) {
} else if (weight.matches("\\d{3}\\d{0}")) {
} else if (weight.matches("\\d{2}\\d{0}")) {
} else {
Toast.makeText(getBaseContext(), "please enter weight in this format : ###.#", Toast.LENGTH_LONG).show();
}

我如何检测到这一点?

PS:当我说##时,我指的是严格的数字

最佳答案

用英语总结您的格式:“2 或 3 位数字,可选地后跟一个小数点和一个数字”,然后将其转换为正则表达式:

[1-9]\d\d?(\.\d)?

在 Java 中:

if (!weight.matches("[1-9]\\d\\d?(\\.\\d)?")) {
Toast.makeText(getBaseContext(), "please enter weight in this format : ###.#", Toast.LENGTH_LONG).show();
}

关于java - 如何检查任何输入的字符串是否采用任何特定格式(###.#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48089095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com