检查字符串在Java中是否只包含数字和逗号
我想检查一些字符串是否只包含数字和逗号,例如: 字符串:1232123111应该可以检查字符串在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))
字符串: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
}