Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查字符串在Java中是否只包含数字和逗号_Java_String_Numbers_Comma - Fatal编程技术网

检查字符串在Java中是否只包含数字和逗号

检查字符串在Java中是否只包含数字和逗号,java,string,numbers,comma,Java,String,Numbers,Comma,我想检查一些字符串是否只包含数字和逗号,例如: 字符串:1232123111应该可以 字符串:fe,32423,4,dsd-应该不正确。您可以使用StringTokenizer或使用string.split()执行此操作。 试试这个正则表达式 String regex = "[0-9, /,]+"; // Negative test cases, should all be "false" System.out.println("1234,234,345a".matches(regex))

我想检查一些字符串是否只包含数字和逗号,例如:

字符串:1232123111应该可以
字符串:fe,32423,4,dsd-应该不正确。

您可以使用
StringTokenizer
或使用
string.split()执行此操作。

试试这个正则表达式

  String regex = "[0-9, /,]+";

// Negative test cases, should all be "false"
System.out.println("1234,234,345a".matches(regex)); //incorrect, So False will be print
     // positive test cases, should all be "true"
  System.out.println("1234,234,34".matches(regex)); //Correct, So True will be print

请参见

这将实现以下功能:

if (!(Pattern.compile("[^0-9,]").matcher(test).find())) {
    //the string only contains numbers and commas
} else {
    //to do if there are invalid characters
}

只需确保导入
java.util.regex.Pattern
library

您可以使用非常基本的regex…到目前为止您尝试了什么?谢谢,它非常有效“11918 1222”此输入也为我提供了正确的值
if (!(Pattern.compile("[^0-9,]").matcher(test).find())) {
    //the string only contains numbers and commas
} else {
    //to do if there are invalid characters
}