繁体   English   中英

检查字符串是否包含任何非数字字符 - 没有库 - Java

[英]Check if string contains any non digit character - no libraries - Java

对于熟悉正则表达式的人来说,这可能很清楚,但我不是。

例子:

String onlyNumbers = "1233444";
String numbersAndDigits = "123344FF";

if (IS_ONLY_NUMBERS(onlyNumbers))
    return true;

if (IS_ONLY_NUMBERS(numbersAndDigits))
    return false;

建议? 有没有办法在不导入库的情况下进行类似的检查?

尝试使用String.matches("\\\\d+") 如果该语句返回 false,则字符串中存在非数字字符。 \\d表示字符必须是数字, +表示每个字符都必须是数字。

像这样:

String onlynumbers = "1233444";
String numbersanddigits = "123344FF";

System.out.println(onlynumbers.matches("\\d+")); // prints "true"
System.out.println(numbersanddigits.matches("\\d+")); // prints "false"

您可以尝试:

if (onlynumbers.matches("[0-9]+")
    return true;

if (numbersanddigits.matches("[0-9]+")
    return false;

此外,作为快捷方式,您可以使用\\\\d+而不是[0-9]+ 选择哪一个只是一个选择问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM