With the help of groups in RegEx we can group several characters together and then use other properties of RegEx on them. We use parenthesis () for make groups in RegEx.


RegEx (Regular Expression) Groups In JavaScript - 5


Regex Groups

We can understand groups in RegEx by the following examples:


Example 1 : In this example, we have grouped the "code" word and then use quantifiers on it.


let regex = /(code){2}/;  // code word two times

let string = "codecodexradar";

let result = regex.exec(string);

if(regex.test(string)) {

console.log(result);

console.log(`The string "${string}" matches the expression "${regex.source}"`);

}else {

console.log(`The string "${string}" does not match the expression "${regex.source}"`);

code-box


Output : The string "codecodexradar" matches the expression "(code){2}"


Example2 : In this example, we have grouped the "code" word and any digits with "r" then use quantifiers on it.


let regex = /(code){2}([0-9]r){3}/;  // code word two times + three times  any digits with r

let string = "codecode1r2r3r";

let result = regex.exec(string);

if(regex.test(string)) {

console.log(result);

console.log(`The string "${string}" matches the expression "${regex.source}"`);

}else {

console.log(`The string "${string}" does not match the expression "${regex.source}"`);

code-box


Output : The string "codecode1r2r3r" matches the expression "(code){2}([0-9]r){3}"


Summary

In this post, we learned about regular expressions groups in JavaScript. Now you practice this. Keep visiting the blog to read more new similar posts.

Post a Comment

Previous Post Next Post