Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/338.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_Regex - Fatal编程技术网

Java 根据特殊字符(逗号除外)验证字符串

Java 根据特殊字符(逗号除外)验证字符串,java,regex,Java,Regex,我一直在尝试根据逗号以外的特殊字符验证字符串 这就是我所做的: if (str.matches("[A-Z0-9, ]*")) System.out.println("Special char present"); 但它工作不正常。如何修复此问题?您似乎忘记了否定您的条件,因为现在它只检查字符串是否只包含A-Z0-9,。如果您想要相反的条件,请尝试使用 if (!str.matches("[A-Z0-9, ]*")) // ^- add th

我一直在尝试根据逗号以外的特殊字符验证字符串

这就是我所做的:

        if (str.matches("[A-Z0-9, ]*")) 
               System.out.println("Special char present");

但它工作不正常。如何修复此问题?

您似乎忘记了否定您的条件,因为现在它只检查字符串是否只包含
A-Z
0-9
。如果您想要相反的条件,请尝试使用

if (!str.matches("[A-Z0-9, ]*")) 
//  ^- add this exclamation mark which represents negation
    System.out.println("Special char present");

定义无法正常工作。您要针对哪些字符串进行测试?哪些有效,哪些无效,为什么?如果你的问题是小写字母,你也需要将它们添加到类中
“[A-Za-z0-9,]*”
。你对特殊字符的定义是什么?小写字符也被认为是特殊的吗?我的字符串应该只包含大写字母,数字和逗号。但是,当我试图通过传递分号来测试它时,它不会打印线[A-Za-z0-9,]*@AlexandruSeverin,根据OP在评论中所说的“我的字符串应该只由大写字母、数字和逗号组成……它也可以由空格组成”我不认为需要小写字符。是的,愚蠢的错误,thx:)