Search

Dark theme | Light theme

September 12, 2025

Groovy Goodness: Accessing Regular Expression Named Groups By Name

Groovy (and Java) support using names for groups in regular expressions. The name of the group is defined using the syntax ?<name> where name must be replaced with the actual group name. This is very useful, because you can use the group name to access the value that is captured by the defined regular expression in a java.util.regex.Matcher object. Groovy supports for a long time accessing a group using the index operator. Since Groovy 5 you can use the name of the group to access the value as well. You can specify the name between square brackets ([<name>]) or use the name as property.

In the following example a Matcher is created based on a Pattern with named groups and the value of the groups is fetched using the name of the group:

// Using named groups language and framework
// in the regular expression of the Pattern.
def group = ('groovy and grails' =~ /(?<language>\w+) and (?<framework>\w+)/)

// Access group using index operator.
assert group[0][1] == 'groovy'

// Since Groovy 5 you can use the name
// of the group to access the value
// with the index operator.
assert group[0]['language'] == 'groovy'

// Or use group name as property.
assert group[0].language == 'groovy'


assert group[0][2] == 'grails'
assert group[0]['framework'] == 'grails'
assert group[0].framework == 'grails'

Written with Groovy 5.0.0.