Non capturing group help to don't get unwanted data in capturing groups.
For instance you string look like
abc and bcd
def or cef
Here you want to capture first and third column data which is separated by and && or
. so you write the regex as follows
(\w+)\s+(and|or)\s+(\w+)
Here $1
contain first column
abc def
then $3
contain
bcd cef
and then unnecessary data stored in to the $2
which is and or
. In this case you don't want to store the unnecessary data so will use non capturing group.
(\w+)\s+(?:and|or)\s+(\w+)
Here $1 contain
abc
def
$2 contain
bcd
def
And will get the exact data from the non capturing group.
For example
(?:don't (want))
Now the $1
contain the data want
.
Then it also help to perform the |
condition inside grouping. For example
(?:don't(want)|some(what))
In the above example $1
contain the data want
and the $2
contain the data what
.