Match values with glob expressions
Turn on the gex option to let a pattern value use * and ? to match many values.
Use this when a pattern should match a family of values, such as every command that starts with l. With the gex option on, a pattern value that has a * or a ? in it is a glob: * stands for any run of characters and ? for any one.
const patrun = require('patrun')
const pm = patrun({ gex: true })
.add({ a: 10 }, 'A')
.add({ a: '1*' }, 'AA')
.add({ a: '*' }, 'AAA')
.add({ b: 1, c: 'x*y' }, 'BC')
pm.find({ a: 10 }) // → 'A' exact
pm.find({ a: 12 }) // → 'AA' glob
pm.find({ a: 2 }) // → 'AAA' star
pm.find({ b: 1, c: 'xhy' }) // → 'BC' exact and glob
A * on its own is not a glob. It is the star of Match any value of a key, the same with or without the option.
When two globs for the same key both match, the narrower one wins, whichever was added first:
const patrun = require('patrun')
const pm = patrun({ gex: true })
.add({ a: 'a*' }, 'STARTS-A')
.add({ a: 'ab*' }, 'STARTS-AB')
.add({ a: 'a?' }, 'A-AND-ONE')
.add({ a: '*a*' }, 'HAS-A')
pm.find({ a: 'abc' }) // → 'STARTS-AB' two fixed characters
pm.find({ a: 'ax' }) // → 'A-AND-ONE' a? before a*
pm.find({ a: 'axy' }) // → 'STARTS-A' a* before *a*
pm.find({ a: 'xa' }) // → 'HAS-A'
In Go #
Set Options.Gex:
pm := patrun.New(patrun.Options{Gex: true})
pm.Add(map[string]string{"a": "10"}, s("A"))
pm.Add(map[string]string{"a": "1*"}, s("AA"))
pm.Add(map[string]string{"a": "*"}, s("AAA"))
pm.Find(map[string]string{"a": "10"}) // → "A"
pm.Find(map[string]string{"a": "12"}) // → "AA"
pm.Find(map[string]string{"a": "2"}) // → "AAA"
In Go, a glob must be valid UTF-8 to be compiled. A value with * or ? that is not valid UTF-8 is an exact value.
What to watch for #
An exact value beats a glob, and a glob beats the star. To write a literal * or ? in a glob, double it: ** is a star itself and *? a question mark itself. The order of two globs is in How a match is chosen. The globs are those of the gex library.