Intersection of Multiple Classes

You can intersect the same class more than once. [0-9&&0-6&&4-9] is the same as [4-6] as those are the only digits present in all three parts of the intersection. You can write the same regex as [0-9&&[0-6]&&[4-9]],[0-9&&[0-6&&4-9]][0-9&&[0-6]&&4-9][0-9&&0-6&&[4-9]], or [0-9&&[0-6&&[4-9]]]. The nested square brackets are only needed if one of the parts of the intersection is negated.
If you do not use square brackets around the right hand part of the intersection, then there is no confusion that the entire remainder of the character class is the right hand part of the intersection. If you do use the square brackets, you could write something like [0-9&&[12]56]. In Ruby, this is the same as [0-9&&1256]. But Java has bugs that cause it to treat this as [0-9&&56], completely ignoring the nested brackets.
You also shouldn't put && at the very start or very end of the regex. Ruby treats [0-9&&] and [&&0-9] is as intersections with an empty class, which matches no characters at all. Java ignores leading and trailing && operators.

Post a Comment

0 Comments