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.
The example below matches any word that occurs twice separated by a space:
let repeatStr = "regex regex";Using the
let repeatRegex = /(\w+)\s\1/;
repeatRegex.test(repeatStr); // Returns true
repeatStr.match(repeatRegex); // Returns ["regex regex", "regex"]
.match()
method on a string will return an array with the string it matches, along with its capture group.
capture groups
in reRegex
to match numbers that are repeated only three times in a string, each separated by a space.
"42 42 42"
.
testString: 'assert(reRegex.test("42 42 42"), ''Your regex should match "42 42 42"
.'');'
- text: Your regex should match "100 100 100"
.
testString: 'assert(reRegex.test("100 100 100"), ''Your regex should match "100 100 100"
.'');'
- text: Your regex should not match "42 42 42 42"
.
testString: 'assert.equal(("42 42 42 42").match(reRegex.source), null, ''Your regex should not match "42 42 42 42"
.'');'
- text: Your regex should not match "42 42"
.
testString: 'assert.equal(("42 42").match(reRegex.source), null, ''Your regex should not match "42 42"
.'');'
- text: Your regex should not match "101 102 103"
.
testString: 'assert(!reRegex.test("101 102 103"), ''Your regex should not match "101 102 103"
.'');'
- text: Your regex should not match "1 2 3"
.
testString: 'assert(!reRegex.test("1 2 3"), ''Your regex should not match "1 2 3"
.'');'
- text: Your regex should match "10 10 10"
.
testString: 'assert(reRegex.test("10 10 10"), ''Your regex should match "10 10 10"
.'');'
```