java - 检查字符串是否包含Java中的数字值

标签 java

如何编写一个方法来查找给定字符串是否包含数字?如果字符串包含数字,则该方法应返回 true,否则返回 false。

最佳答案

if(str.matches(".*\\d.*")){
   // contains a number
} else{
   // does not contain a number
}

以前建议的解决方案,不起作用,但由于@Eng.Fouad 的请求/建议而恢复。

建议的解决方案不起作用

String strWithNumber = "This string has a 1 number";
String strWithoutNumber = "This string does not have a number";

System.out.println(strWithNumber.contains("\d"));
System.out.println(strWithoutNumber.contains("\d"));

工作解决方案

String strWithNumber = "This string has a 1 number";
if(strWithNumber.matches(".*\\d.*")){
    System.out.println("'"+strWithNumber+"' contains digit");
} else{
    System.out.println("'"+strWithNumber+"' does not contain a digit");
}

String strWithoutNumber = "This string does not have a number";
if(strWithoutNumber.matches(".*\\d.*")){
    System.out.println("'"+strWithoutNumber+"' contains digit");
} else{
    System.out.println("'"+strWithoutNumber+"' does not contain a digit");
}

输出

'This string has a 1 number' contains digit
'This string does not have a number' does not contain a digit

关于java - 检查字符串是否包含Java中的数字值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6344867/

相关文章:

java - 如何贡献 Action 与 Eclipse 中的菜单进行比较

java - 使用埃拉托色尼筛法生成 k 个素数

java - ServiceMix (FuseESB) - 无法使用 AggregationStrategy 部署服务单元

java - 字符串的最大匹配

java - libGDX 动画纹理区域

java - java中如何分割字符串?

java - jpa映射两个属性

java - 可以使用共享的 Random 实例来获得高斯分布吗

java - 如何避免重复出现相同的号码?

使用 Protocol Buffer 进行 Java 序列化