





- Garden Text Representation
let garden = [
"Snow-in-Summer",
"Snow-on-the-Mountain",
"Rose-of-Sharon"
];
- Code Editor
- Log
for (const plant of garden) {
if (plant.match(//i) {
fertilize(plant);
}
}
Lesson task •
Fertilize plants having more than 2 dash symbols in their names
Non-capturing group
(?:...)
Groups repetitive patterns but without saving it into variablesIn Capturing groups we've seen that the brackets can be used to reuse repetitive patterns inside regular expressions. But capturing groups are not the best option for it - the main purpose of capturing groups is "capturing" match into local variable for the later replacement.
In case you don't need the replacement with a matched pattern, you can use non-capturing group: it doesn't save the matched pattern to a local variable and thus saves memory. Replacing capturing groups with non-capturing groups optimizes performance of the regular expression. Use it whenever you can.
console.log(!!"foo".match(/(foo\s*){3,}/i)) // false
console.log(!!"foo".match(/(?:foo\s*){3,}/i)) // false
console.log(!!"foo foo".match(/(foo\s*){3,}/i)) // false
console.log(!!"foo foo".match(/(?:foo\s*){3,}/i)) // false
console.log(!!"foo foo foo".match(/(foo\s*){3,}/i)) // true
console.log(!!"foo foo foo".match(/(?:foo\s*){3,}/i)) // true
Remember: non-capturing groups are more performant in grouping repetitive patterns inside regular expressions than capturing groups, but are not suitable for using these repetitive patterns for replacement:
console.log("Isaac Asimov".replace(/(\w+) (\w+)/i, "$2, $1")) // Asimov, Isaac
console.log("Isaac Asimov".replace(/(?:\w+) (?:\w+)/i, "$2, $1")) // $2, $1
console.log("4 8 15 16 23 42".replace(/(\d+) (\d+) (\d+) (\d+) (\d+) (\d+)/i, "$6 $5 $4 $3 $2 $1")) // 42 23 16 15 8 4
console.log("4 8 15 16 23 42".replace(/(?:\d+) (?:\d+) (?:\d+) (?:\d+) (?:\d+) (?:\d+)/i, "$6 $5 $4 $3 $2 $1")) // $6 $5 $4 $3 $2 $1