Intersection in Negated Classes

The character class [^1234&&3456] is both negated and intersected. In Java, negation takes precedence over intersection. Java reads this regex as "(not 1234) and 3456". Thus in Java this class is the same as [56] and matches the digits 5 and 6. In Ruby, intersection takes precedence over negation. Ruby reads [^1234&&3456] as "not (1234 and 3456)". Thus in Ruby this class is the same as [^34] which matches anything except the digits 3 and 4.
If you want to negate the right hand side of the intersection, then you must use square brackets. Those automatically control precedence. So both Java and Ruby read [1234&&[^3456]] as "1234 and (not 3456)". Thus this regex is the same as [12].

Post a Comment