Capturing Groups in JavaScript Regular Expressions

Capturing Groups in JavaScript Regular Expressions

Capturing Groups in JavaScript Regular Expressions

In JavaScript regular expressions, capturing groups allow you to group parts of your regular expression together so that you can extract matched substrings from the string. Capturing groups are defined by enclosing part of the regular expression in parentheses ().

Once a group is captured, you can access it using the match(), exec(), or replace() methods.

1. Syntax of Capturing Groups

A capturing group is created by placing part of the regular expression inside parentheses:

let pattern = /(abc)/;
  • (abc) is a capturing group. It matches the exact sequence of characters "abc".
  • When a string is matched, the part of the string corresponding to the group can be retrieved.

2. Example: Basic Capturing Group

Example: Extracting a Substring

let pattern = /(abc)/; let str = "abcdef"; let result = str.match(pattern); console.log(result[0]); // "abc" (full match) console.log(result[1]); // "abc" (first capturing group)
  • result[0] contains the entire match (the full string that matched the regular expression).
  • result[1] contains the first capturing group, which is "abc" in this case.

Explanation:

  • The regular expression /(abc)/ matches "abc" in the string "abcdef".
  • The captured substring "abc" is stored in result[1].

3. Multiple Capturing Groups

You can have multiple capturing groups in a single regular expression. Each group will be indexed starting from 1.

Example: Multiple Capturing Groups

let pattern = /(\d{3})-(\d{2})-(\d{4})/; let str = "123-45-6789"; let result = str.match(pattern); console.log(result[0]); // "123-45-6789" (full match) console.log(result[1]); // "123" (first capturing group) console.log(result[2]); // "45" (second capturing group) console.log(result[3]); // "6789" (third capturing group)
  • The regular expression (\d{3})-(\d{2})-(\d{4}) matches a string in the format of a social security number (e.g., 123-45-6789).
  • It contains three capturing groups:
    1. (\d{3}): Matches the first three digits (123).
    2. (\d{2}): Matches the next two digits (45).
    3. (\d{4}): Matches the last four digits (6789).

The result array contains the full match as the first element (result[0]), followed by the matched substrings for each group (result[1], result[2], result[3]).

4. Accessing Captured Groups Using exec()

The exec() method also returns an array containing the full match and the captured groups. It's useful when you want to repeatedly match patterns in a string using a global regular expression.

Example: Using exec() to Capture Groups

let pattern = /(\d{3})-(\d{2})-(\d{4})/; let str = "123-45-6789"; let result = pattern.exec(str); console.log(result[0]); // "123-45-6789" (full match) console.log(result[1]); // "123" (first capturing group) console.log(result[2]); // "45" (second capturing group) console.log(result[3]); // "6789" (third capturing group)
  • exec() returns the same kind of array as match(), but it also works well with global regular expressions and can be used to iterate over multiple matches.

5. Named Capturing Groups (ES6)

Since ECMAScript 2018 (ES6), JavaScript supports named capturing groups. Named groups allow you to access the captured data using the name you provide instead of using the numeric index.

Syntax for Named Capturing Groups:

let pattern = /(?<name>[a-z]+)/;
  • (?<name>[a-z]+) defines a named capturing group called name that matches one or more lowercase letters.

Example: Using Named Capturing Groups

let pattern = /(?<areaCode>\d{3})-(?<prefix>\d{2})-(?<lineNumber>\d{4})/; let str = "123-45-6789"; let result = str.match(pattern); console.log(result.groups.areaCode); // "123" console.log(result.groups.prefix); // "45" console.log(result.groups.lineNumber); // "6789"
  • (?<areaCode>\d{3}) is a named capturing group for the area code.
  • (?<prefix>\d{2}) is a named capturing group for the prefix.
  • (?<lineNumber>\d{4}) is a named capturing group for the line number.
  • The captured groups are accessed via result.groups.<name>.

6. Using Capturing Groups with replace()

You can use captured groups in string replacements with the replace() method. When you call replace(), you can reference the captured groups using $1, $2, etc., or use named groups with ${name}.

Example: Using Capturing Groups with replace()

let pattern = /(\d{3})-(\d{2})-(\d{4})/; let str = "123-45-6789"; let result = str.replace(pattern, "($1) $2-$3"); console.log(result); // "(123) 45-6789"
  • $1, $2, and $3 refer to the captured groups.
  • The replace() method inserts the captured groups into the new format ($1) $2-$3.

7. Non-Capturing Groups

If you want to group parts of a regular expression without capturing them (i.e., you don’t need to retrieve them), you can use non-capturing groups by using (?:...).

Example: Non-Capturing Groups

let pattern = /(?:\d{3})-(\d{2})-(\d{4})/; let str = "123-45-6789"; let result = str.match(pattern); console.log(result[0]); // "45-6789" console.log(result[1]); // "45"
  • (?:\d{3}) is a non-capturing group, meaning it groups the \d{3} without storing it for later use.
  • The capturing group (\d{2}) stores the matched value 45.

8. Conclusion

Capturing groups in JavaScript regular expressions allow you to:

  • Group parts of the pattern together for extraction.
  • Access matched substrings using numeric or named indices.
  • Use captured groups in string replacements with replace().

Capturing groups are essential when you need to extract or manipulate specific parts of a string that match a regular expression pattern. You can use them in various ways, such as matching and extracting parts of text, modifying text, or working with patterns in more advanced scenarios.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close