- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Regex - reusing patterns to capture groups in JavaScript?
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
Advertisements