I have gone through the docs for Atomic Grouping and rubyinfo and some questions came into my mind:
I tried the below code to understand but had confusion about the output and how differently they work on the same string as well?
irb(main):001:0> /a(?>bc|b)c/ =~ "abbcdabcc" => 5 irb(main):004:0> $~ => #<MatchData "abcc"> irb(main):005:0> /a(bc|b)c/ =~ "abcdabcc" => 0 irb(main):006:0> $~ => #<MatchData "abc" 1:"b">
An atomic group is a group that, when the regex engine exits from it, automatically throws away all backtracking positions remembered by any tokens inside the group. Atomic groups are non-capturing. The syntax is (?> group).
Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".
tl;dr non-capturing groups, as the name suggests are the parts of the regex that you do not want to be included in the match and ?: is a way to define a group as being non-capturing. Let's say you have an email address [email protected] . The following regex will create two groups, the id part and @example.com part.
=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.
A ()
has some properties (include those such as (?!pattern)
, (?=pattern)
, etc. and the plain (pattern)
), but the common property between all of them is grouping, which makes the arbitrary pattern a single unit (unit is my own terminology), which is useful in repetition.
The normal capturing (pattern)
has the property of capturing and group. Capturing means that the text matches the pattern inside will be captured so that you can use it with back-reference, in matching or replacement. The non-capturing group (?:pattern)
doesn't have the capturing property, so it will save a bit of space and speed up a bit compared to (pattern)
since it doesn't store the start and end index of the string matching the pattern inside.
Atomic grouping (?>pattern)
also has the non-capturing property, so the position of the text matched inside will not be captured.
Atomic grouping adds property of atomic compared to capturing or non-capturing group. Atomic here means: at the current position, find the first sequence (first is defined by how the engine matches according to the pattern given) that matches the pattern inside atomic grouping and hold on to it (so backtracking is disallowed).
A group without atomicity will allow backtracking - it will still find the first sequence, then if the matching ahead fails, it will backtrack and find the next sequence, until a match for the entire regex expression is found or all possibilities are exhausted.
Example
Input string: bbabbbabbbbc
Pattern: /(?>.*)c/
The first match by .*
is bbabbbabbbbc
due to the greedy quantifier *
. It will hold on to this match, disallowing c
from matching. The matcher will retry at the next position to the end of the string, and the same thing happens. So nothing matches the regex at all.
Input string: bbabbbabbbbc
Pattern: /((?>.*)|b*)[ac]/
, for testing /(((?>.*))|(b*))[ac]/
There are 3 matches to this regex, which are bba
, bbba
, bbbbc
. If you use the 2nd regex, which is the same but with capturing groups added for debugging purpose, you can see that all the matches are result of matching b*
inside.
You can see the backtracking behavior here.
Without the atomic grouping /(.*|b*)[ac]/
, the string will have a single match which is the whole string, due to backtracking at the end to match [ac]
. Note that the engine will go back to .*
to backtrack by 1 character since it still have other possibilities.
Pattern: /(.*|b*)[ac]/ bbabbbabbbbc ^ -- Start matching. Look at first item in alternation: .* bbabbbabbbbc ^ -- First match of .*, due to greedy quantifier bbabbbabbbbc X -- [ac] cannot match -- Backtrack to () bbabbbabbbbc ^ -- Continue explore other possibility with .* -- Step back 1 character bbabbbabbbbc ^ -- [ac] matches, end of regex, a match is found
With the atomic grouping, all possibilities of .*
is cut off and limited to the first match. So after greedily eating the whole string and fail to match, the engine have to go for the b*
pattern, where it successfully finds a match to the regex.
Pattern: /((?>.*)|b*)[ac]/ bbabbbabbbbc ^ -- Start matching. Look at first item in alternation: (?>.*) bbabbbabbbbc ^ -- First match of .*, due to greedy quantifier -- The atomic grouping will disallow .* to be backtracked and rematched bbabbbabbbbc X -- [ac] cannot match -- Backtrack to () -- (?>.*) is atomic, check the next possibility by alternation: b* bbabbbabbbbc ^ -- Starting to rematch with b* bbabbbabbbbc ^ -- First match with b*, due to greedy quantifier bbabbbabbbbc ^ -- [ac] matches, end of regex, a match is found
The subsequent matches will continue on from here.
I recently had to explain Atomic Groups to someone else and I thought I'd tweak and share the example here.
Consider /the (big|small|biggest) (cat|dog|bird)/
Matches in bold
DEMO
For the first line, a regex engine would find the
. It would then proceed on to our adjectives (big
, small
, biggest
), it finds big
. Having matched big
, it proceeds and finds the space. It then looks at our pets (cat
, dog
, bird
), finds cat
, skips it, and finds dog
.
For the second line, our regex would find the
. It would proceed and look at big
, skip it, look at and find small
. It finds the space, skips cat
and dog
because they don't match, and finds bird
.
For the third line, our regex would find the
, It continues on and finds big
which matches the immediate requirement, and proceeds. It can't find the space, so it backtracks (rewinds the position to the last choice it made). It skips big
, skips small
, and finds biggest
which also matches the immediate requirement. It then finds the space. It skips cat
, and matches dog
.
For the fourth line, our regex would find the
. It would proceed to look at big
, skip it, look at and find small
. It then finds the space. It looks at and matches cat
.
Consider /the (?>big|small|biggest) (cat|dog|bird)/
Note the ?>
atomic group on adjectives.
Matches in bold
DEMO
For the first line, second line, and fourth line, we'll get the same result.
For the third line, our regex would find the
, It continues on and find big
which matches the immediate requirement, and proceeds. It can't find the space, but the atomic group, being the last choice the engine made, won't allow that choice to be re-examined (prohibits backtracking). Since it can't make a new choice, the match has to fail, since our simple expression has no other choices.
This is only a basic summary. An engine wouldn't need to look at the entirety of cat
to know that it doesn't match dog
, merely looking at the c
is enough. When trying to match bird, the c
in cat
and the d
in dog are enough to tell the engine to examine other options.
However if you had ...((cat|snake)|dog|bird)
, the engine would also, of course, need to examine snake before it dropped to the previous group and examined dog and bird.
There are also plenty of choices an engine can't decide without going past what may not seem like a match, which is what results in backtracking. If you have ((red)?cat|dog|bird)
, The engine will look at r
, back out, notice the ?
quantifier, ignore the subgroup (red)
, and look for a match.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With