I was reading the topic grouping in Regex from the doc Grouping.I found there one example and started to play with it to understand the behaviors/roles of ?<option>: in Regex. The code is used to undersatnd it as below:
%w{CASE case CAse caSE cASe casE}.grep /(?i:ca)se/
# => ["case", "CAse"]
%w{CASE case CAse caSE cASe casE}.grep /(?:ca)se/
# => ["case"]
%w{CASE case CAse caSE cASe casE}.grep /(:ca)se/
# => []
%w{CASE case CAse caSE cASe casE}.grep /(i:ca)se/
# => []
Now I am totally confused about the operations performed by (?i:ca,(?:ca)se,(:ca),(i:ca). Each syntax is valid as per the output,otherwise I might get error from the console.
Could any one please help me to understand how the outputs have been generated by the code above, and what the special roles are of ?<option>: in grouping of Regex?
Non-capturing group
(?<option>:pattern), with case-insensitive flag oni. The pattern isca. The case-insensitive flag is only effective within the non-capturing group, socais matched case-insensitive, whileseis matched case-sensitive. This is a useful construct to activate certain effect for only part of the regex.Non-capturing group will not store the position of the text matched by the pattern inside the group, as opposed to capturing group
(pattern)that doesn’t start with?after(.This is just a plain non-capturing group without any option, with
caas pattern. As the document described, the<option>in(?<option>:pattern)can be empty. There is nothing special here, just match case-sensitively.This is a capturing group, with
:caas pattern (colon:,cthena). Of course, no match found.Again, a capturing group, with
i:caas pattern (i, colon:,c, thena). No match found also.