Search code examples
rubyregexcharacter-class

Ruby regular expression utilizing OR within a character class


While going through the ruby-doc for regular expressions, I came across this example for implementing the && operator:

/[a-w&&[^c-g]z]/ # ([a-w] AND ([^c-g] OR z))
# This is equivalent to:
/[abh-w]/

I understand that

/[a-w&&[^c-g]]/ 

would equate to

/[abh-w]/

because the "^" denotes symbols that should be excluded from the regular expression.

However, I am wondering about why "z" is not also included? Why was the equivalent regular expression NOT:

/[abh-wz]/

I am very new to regular expressions, much less any specifics for regular expressions within Ruby, so any help is greatly appreciated!


Solution

  • The page explicitly says:

    /[a-w&&[^c-g]z]/ # ([a-w] AND ([^c-g] OR z))
    # This is equivalent to:
    /[abh-w]/
    

    "z" is not included in the left "AND" term, so it can't be matched.

    See: "All things that are both apples, and also either apples or pears, at the same time" does not include pears. Only apples are both apples and (apples or pears). Likewise, a is in both a-w and [^c-g]z, so it matches; z is not in the left side, so "AND" is not satisfied, thus the whole expression fails.