java 中的正则表达式否定如何否定嵌套的 类

How regex negation in java negate nested classes

我有下面的程序来替换特殊字符

      String a = "fgA9.^";
       String b ="";
       a = a.replaceAll("[^[a-zA-Z0-9]]", b);
       System.out.println(a); 

这会打印 (.^) 作为输出,但我希望正则表达式模式否定字母、数字并替换特殊字符。

我可以通过 a = a.replaceAll("[[^a-zA-Z0-9]]", b);

看到我的预期输出

两者有什么区别,在这两种情况下我都使用了否定?

使用嵌套字符 class,您创建了 union:

You can also use unions to create a single character class comprised of two or more separate character classes. To create a union, simply nest one class inside the other, such as [0-4[6-8]]. This particular union creates a single character class that matches the numbers 0, 1, 2, 3, 4, 6, 7, and 8.

"[^[a-zA-Z0-9]]" 正则表达式匹配字母数字字符,因为该模式由 [^](忽略空联合部分)和匹配 ASCII 字母和数字的 [a-zA-Z0-9] 组成。

[[^a-zA-Z0-9]] 模式中,您指定了一个否定字符 class [^a-zA-Z0-9] 匹配除 ASCII letter/digit 以外的任何字符,并再次与空部分联合, 忽略。

[0-4[6-8]] 正则表达式在语义上完全等同于 [0-46-8],并且在组合否定字符和肯定字符 classes 时可以观察到更实用的联合值。例如。 [^\p{L}[a-c]]+ 将匹配除字母 ([^\p{L}]) 和三个小写 abc 字符之外的一个或多个字符。