Skip to content
Build and reuse a pattern

Build a pattern once and reuse it

Build a pattern once and reuse it

Mark the fields in one line, let trex build the pattern that extracts them from every line of that shape, save it as a pattern file, and read new input with it from then on.

Build it from a marked line

Write each value to extract as {name:text}, with [int] or another type before the name where the value has one. The other lines are examples the pattern must also read:

$ trex infer --mark 'GET https://{host:example.com}/a {[int]code:200}' 'GET https://trex.dev/b 404' --lib-file
# Built by trex infer from 2 lines in 1 shape; `extract` names every shape in order.
let extract_1 = ^ "GET" (\U):host (\N):code ~<($ .)
let extract = \{extract_1}
fields extract {host:host} {[int]code}
test extract accepts "GET https://example.com/a 200"

{host:host} reads the host of the URL the field holds. The fields line keeps each field’s name, type and accessor beside the pattern; PowerShell casts a field to its [type], and the other surfaces give its text.

Save it and read with it

Save that text as hosts.trex, then read new lines with \{extract}:

$ cat hosts.trex
let extract_1 = ^ "GET" (\U):host (\N):code ~<($ .)
let extract = \{extract_1}
fields extract {host:host} {[int]code}
$ trex scan '\{extract}' --lib hosts.trex --text 'GET https://example.org/x 500' --fields
record  lines  host         code
1       1      example.org  500

Lines of several layouts build one branch a layout; a pattern that extracts fields has the marks, lists, records and declared shapes a build reads.