Capturing and non-capturing groups are used to group a pattern. In simple words we can treat a set of characters( Eg. [a-zA-Z0-9] and also other special characters and spaces etc. ) as a single unit using capturing and non-capturing group.

Capturing group is represented by parentheses ‘()’ and it is used to capture a group. Let’s understand with an example :

Suppose we have a string : Hello World. Hi World.
The regular expression for matching this pattern is written below

(Hello)\s(World)\.\s(Hi)\s\2\.

There are 3 capturing groups in the above regex example
Group 1: Hello
Group 2: World
Group 3: Hi
And the full match is Hello World. Hi World.
Now let’s full pattern description
(Hello) : Hello inside these two parentheses acts as a group
\s : Represents space here
(World) : World inside these two parentheses acts as a group
\. : Represents the character ‘.’
(Hi) : Hi inside these two parentheses acts as a group
\2 : Represents the second group which is ‘World’ here.
Demo link : https://regex101.com/r/FlBZB9/1
——————————————————————————————————————–

Non-capturing group also represented by parentheses with a question mark ‘?’ and colon ‘:’ inside it which looks like (?:) this. Let’s take the same string as example to understand non-capturing group.

Suppose we have a string : Hello World. Hi World.
The regular expression for matching this pattern and understanding non-capturing group is written below:

(Hello)\s(?:World)\.\s(Hi)\s(World)\.

There are 2 capturing groups in the above regex example
Group 1: Hello
Group 2: Hi
Group 3: World
And the full match is Hello World. Hi World.
Now let’s full pattern description
(Hello) : Hello inside these two parentheses acts as a group
\s : Represents space here
(?:World) : World inside these two parentheses acts as a group but is not captured because of ‘?:’. So it is not second group now
\. : Represents the character ‘.’
(Hi) : Hi inside these two parentheses acts as a group
(World) : Represents the third group which is ‘World’ here. We can not use \2 at this place for the last occurred ‘World’ now because previous ‘World’ group is not captured. Now \2 will be represented for ‘Hi’.

Demo link : https://regex101.com/r/pILxNB/1