1

Named capturing groups in go

2

The simplest way to gain access to any subgroup match in a regexp is by using indexes. This is still my preferred method

3

of choice for one-off tasks, and I use it daily to perform substitutions on my neovim buffers.

4

5

However, when introducing a regular expression into a codebase, I try to use named capture groups instead. They allow

6

you to access the match by a name, and I think they become especially useful for longer and more complex patterns where

7

they can help to serve as documentation.

8

9

Here is one way of using them in Go:

10

11
var re = regexp.MustCompile("This file is (?P<size>[0-9]+)(?P<unit>kb|mb|gb)")
12
 
13
func main() {
14
  str := "This file is 100kb"
15
  match := re.FindSubmatch([]byte(str))
16
  fmt.Println(string(match[re.SubexpIndex("size")])) // 100
17
  fmt.Println(string(match[re.SubexpIndex("unit")])) // kb
18
}
12

13

This is a fairly simple pattern, but I still think it is easier to read compared to its unnamed counter part:

14

15
var re = regexp.MustCompile("This file is ([0-9]+)(kb|mb|gb)")
16
 
17
func main() {
18
  str := "This file is 100kb"
19
  match := re.FindSubmatch([]byte(str))
20
  fmt.Println(string(match[1])) // 100
21
  fmt.Println(string(match[2])) // kb
22
}
15

16

The end

17

I usually tweet something when I've finished writing a new post. You can find me on Twitter

18

by clicking 

normalintroduction.md
||33:3

Recently Edited

Recently Edited

File name

Tags

Time to read

Created at

context

  • go
  • context
8 minutes2024-02-28

circular-buffers

  • go
  • concurrency
  • data processing
5 minutes2024-02-04

go-directives

  • go
  • compiler
  • performance
4 minutes2023-10-21

async-tree-traversals

  • node
  • trees
  • graphs
  • typescript
19 minutes2023-09-10

All Files

All Files

  • go

    5 files

  • node

    2 files

  • typescript

    1 file

  • frontend

    1 file

  • workflow

    7 files