What is a regular expression capture group, why is it needed and how to use it?
- 2usually the regular answer answers the question - does the passed string satisfy the described expression, that is, the answer is: yes / no, the group allows to get a specific part of the string that satisfies the expression - Grundy
1 answer
A capture group is part of a regular expression pattern enclosed in parentheses; if a pattern matches a matching string, that part of the string that matches the pattern in brackets will be placed into the resulting array as a separate element.
Example 1
alert( 'Hello, World!'.match(/World!/) ); // World! https://jsfiddle.net/6jypate5/
In the example above, that part of the line with which the pattern matched is displayed: World! .
Example 2
alert( 'Hello, World!'.match(/World(!)/) ); // World!,! https://jsfiddle.net/pt7geaLx/
In this example, in addition to the part of the line with which the pattern coincided: World! ; the part of the string that matches the pattern in parentheses will also be displayed:! .
A capture group is also called a submask or a subpattern ... Their purpose is not only to put the matched part of the line in the result, but also that they can be accessed from other places of the pattern ...
Literature: