Search This Blog

2024/03/23

Javascript Regular Expression: Non Capturing Group example

Lets observe two code samples below

Code 1:
var pattern = /(animal)(=)(\w+)(,)/gim;
var line1 = "animal=cat,dog,cat,tiger,dog";
if (pattern.test(line1)) {
console.log(RegExp.$1);
console.log(RegExp.$2);
console.log(RegExp.$3);
console.log(RegExp.$4);
}
Output:
animal
=
cat
,
Code 2:
var pattern =/(?:animal)(?:=)(\w+)(,)/igm
var line1 ="animal=cat,dog,cat,tiger,dog"
if(pattern.test(line1)){
console.log(RegExp.$1)
console.log(RegExp.$2)
console.log(RegExp.$3)
console.log(RegExp.$4)
}

Output:
cat
,

Explanation:
Here in above code

(?:animal) --> Non-Captured Group 1

(?:=)--> Non-Captured Group 2

(\w+)--> Captured Group 1

(,)--> Captured Group 2

by giving the ?: we make the match-group non captured.
which do not count off in matched group, so the grouping number
starts from the first captured group and not the non captured,
so that the repetition of the result of match-group (?:animal)
cant be called later in code.


No comments:

Post a Comment