What is the "groups" property in the result of a Regex?

Asked

Viewed 63 times

4

When searching for a certain occurrence in a string with Regex without the flag g (of global), the result comes, in addition to the array with the occurrence found, other properties such as index, input and groups:

inserir a descrição da imagem aqui

var string = "abc";
var re = string.match(/b/);
console.log("Ocorrência:", re);
console.log("Index:", re.index);
console.log("Input:", re.input);
console.log("Groups:", re.groups);

My question is: what is and what is this property for groups?

I thought it would be some captured group, but when I put the b within parentheses to create a group, even though the property groups returns undefined:

inserir a descrição da imagem aqui

var string = "abc";
var re = string.match(/(b)/);
console.log("Ocorrência:", re);
console.log("Index:", re.index);
console.log("Input:", re.input);
console.log("Groups:", re.groups);

1 answer

5


According to the documentation, the property groups contains the named capturing groups (capture groups with name):

An array of named capturing groups or undefined if no named capturing groups Were defined.

In free translation:

An array of capture groups with name or undefined if no named capture group is defined.

A simple capture group (with only parentheses) has no name, so it is not returned in groups. To have a group with name, just use (?<Nome>:

var string = "abc";
var re = string.match(/(?<letra>b)/);
console.log("Ocorrência:", re);
console.log("Index:", re.index);
console.log("Input:", re.input);
console.log("Groups:", re.groups);

In the above case, the group is called "letter", and its value is the letter "b".


Remembering that named capturing groups is a resource that was added in Ecmascript 2018.

  • 1

    Cool guy! I didn’t know this r... thanks anyway!

  • 1

    @Sam The name of the property confuses, right? The first time I saw it, I thought she had all the groups...

  • 1

    Yes, I found it too...

  • 1

    Good answer!! I think I could add that this group feature in regular expressions is from a newer version of Javascript. If I’m not mistaken, ES2018!

  • 1

    @Luizfelipe I was looking for a link with the exact version. Reply updated, thank you! :-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.