DEV Community


Reusing Patterns Using Capture Groups

rthefounding profile image Randy Rivera ・1 min read
  • Some patterns you search for will occur multiple times in a string. It is wasteful to manually repeat that regex. There is a better way to specify when you have multiple repeat substrings in your string.
  • You can search for repeat substrings using capture groups. Parentheses, ( and ), are used to find repeat substrings. You put the regex of the pattern that will repeat in between the parentheses.
  • To specify where that repeat string will appear, you use a backslash (\) and then a number. This number starts at 1 and increases with each additional capture group you use. An example would be \1 to match the first group.
    • Ex:
let repeatNum = "42 42 42";
let reRegex = /^(\d+)\s\1\s\1$/;
let result = reRegex.test(repeatNum);

console.log(result); will display true
Enter fullscreen mode Exit fullscreen mode
  • Here we used capture groups in reRegex that matches a string that consists of only the same number repeated exactly three times separated by single spaces.
  • Using the .match() method on a string will return an array with the string it matches, along with its capture group.

Discussion (0)

Forem Open with the Forem app