Regex - reusing patterns to capture groups in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

For this, use regular expression with digit along with $.

Example

var groupValues1 = "10 10 10";
var groupValues2 = "10 10 10 10";
var groupValues3 = "10 10";
var regularExpression = /^(\d+)(\s)\1\2\1$/;
var isValidGroup1 = regularExpression.test(groupValues1);
var isValidGroup2 = regularExpression.test(groupValues2);
var isValidGroup3 = regularExpression.test(groupValues3);
if(isValidGroup1==true)
   console.log("This is a valid group="+groupValues1);
else
   console.log("This is not a valid group="+groupValues1);
if(isValidGroup2==true)
   console.log("This is a valid group="+groupValues2);
else
   console.log("This is not a valid group="+groupValues2);
if(isValidGroup3==true)
   console.log("This is a valid group="+groupValues3);
else
   console.log("This is not a valid group="+groupValues3);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo188.js.

Output

The below output matches only groups 3. This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo188.js
This is a valid group=10 10 10
This is not a valid group=10 10 10 10
This is not a valid group=10 10
raja
Published on 14-Sep-2020 08:18:41
Advertisements