Access Matched Groupings in JavaScript Regular Expressions
When using regular expressions to match patterns in strings, it's often desirable to access specific portions of the matched text. JavaScript provides several ways to accomplish this.
In your example, you correctly used a regular expression with parentheses to capture a portion of the string. However, the issue you encountered was not with the regex itself but with the way you were accessing the matched groups.
Accessing Groups with .exec()
The .exec() method returns an array containing the entire matched string as the first element, followed by any captured groups. To access the first captured group (the "abc" portion in your example), you would use arr[1]:
let myString = "something format_abc"; let arr = /(?:^|\s)format_(.*?)(?:\s|$)/.exec(myString); console.log(arr[1]); // Prints: abc
Using Named Capture Groups
You can also name your capture groups using regular expressions syntax like (?
let myString = "something format_abc"; let arr = /(?:^|\s)format_(?<text>.*?)(?:\s|$)/.exec(myString); console.log(arr.groups.text); // Prints: abc
Alternate Syntax with Named Capture Groups:
In ECMAScript 2018, you can use a slightly different syntax for named capture groups, enclosing the group name in curly braces:
let myString = "something format_abc"; let arr = /(?:^|\s)format_({text}.*?)(?:\s|$)/.exec(myString); console.log(arr.groups.text); // Prints: abc
Matching Multiple Occurrences with .matchAll()
The .matchAll() method was introduced in ECMAScript 2020 and provides an iterator-based API for matching multiple occurrences of a pattern in a string. It returns an iterator that yields match results as an array for each match, and you can access the captured groups within each result.
To use .matchAll() in your example:
let myString = "something format_abc and something format_xyz"; let matches = myString.matchAll(/(?:^|\s)format_(.*?)(?:\s|$)/g); for (let match of matches) { console.log(match[1]); // Prints: abc, then xyz }
The above is the detailed content of How Can I Access Matched Groups in JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!