liveBook · Manning

Regexp package

As explained in Learn Go with Pocket-Sized Projects

regexp is Go's standard-library package for compiling and applying regular expressions.

The regexp package compiles and applies regular expressions in Go. It helps tests validate generated values without depending on unpredictable runtime identifiers. section 8.5.2

Finding an identifier in JSON

Compile `.+"id":"([a-zA-Z0-9]+)".+` with regexp.MustCompile, then call FindStringSubmatch. The captured value is returned separately, allowing the test to replace the generated ID before comparing JSON. section 8.5.2

Listing 8.37 newgame/handler_test.go: Replacing the ID in JSON output
// idFinderRegexp is a regular expression that will ensure the body
// contains an id field with a value that contains
// only letters (uppercase and/or lowercase) and/or digits.
idFinderRegexp := regexp.MustCompile(
    `.+"id":"([a-zA-Z0-9]+)".+`) #1

id := idFinderRegexp.FindStringSubmatch(body) #2
if len(id) != 2 { #3
    t.Fatal("cannot find one id in the json output")
}
body = strings.Replace(body, id[1], "123456", 1) #4

assert.JSONEq(t, testCase.wantBody, body) #5

Shows compiled-pattern matching, capture extraction, length checking, and deterministic replacement in a handler test. section 8.5.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains compilation, quantifiers, character ranges, capture groups, and match extraction, without covering broader package options.
Examples
Uses JSON containing an ID, FindStringSubmatch, strings.Replace, assert.JSONEq, and an alphanumeric ID assertion.
What it assumes
Assumes familiarity with Go tests, JSON responses, generated IDs, and string replacement.
What you can do after
Diagnose and test generated string values by compiling patterns, extracting captures, and normalizing nondeterministic output.
How it connects
Connects regular expressions with Go testing, JSON comparison, generated identifiers, and string replacement.

Also explained in

Compare how 2 books explain regexp package →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.