有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

这就是我所做的:

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

但它没有正常工作。如何解决这个问题


共 (1) 个答案

  1. # 1 楼答案

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

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