Confusion with Atomic Grouping - how it differs from the Grouping in regular expression of Ruby?

后端 未结 3 1932
情歌与酒
情歌与酒 2020-12-02 09:30

I just gone through the docs for Atomic Grouping and rubyinfo and some quick questions came into my mind as follows:

  1. Why the name came as \"Atomic
3条回答
  •  温柔的废话
    2020-12-02 10:18

    An "atomic group" is one where the regular expression will never backtrack past. So in your first example /a(?>bc|b)c/ if the bc alternation in the group matches, then it will never backtrack out of that and try the b alternation. If you slightly alter your first example to match against "abcdabcc" then you'll see it still matches the "abcc" at the end of the string instead of the "abc" at the start. If you don't use an atomic group, then it can backtrack past the bc and try the b alternation and end up matching the "abc" at the start.

    As for question two, how it's different, that's just a rephrasing of your first question.

    And lastly, atomic groups are not "called" non-capturing groups. That's not an alternate name for them. Non-capturing groups are groups that do not capture their content. Typically when you match a regular expression against a string, you can retrieve all the matched groups, and if you use a substitution, you can use backreferences in the substitution like \1 to insert the captured groups there. But a non-capturing group does not provide this. The classic non-capturing group is (?:pattern). An atomic group happens to also have the non-capturing property, hence why it's called a non-capturing group.

提交回复
热议问题