https://github.com/fclairamb/restruct
https://github.com/fclairamb/restruct
Last synced: about 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/fclairamb/restruct
- Owner: fclairamb
- License: mit
- Created: 2022-09-06T20:53:34.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2024-11-23T13:42:15.000Z (over 1 year ago)
- Last Synced: 2025-03-23T22:53:24.956Z (about 1 year ago)
- Language: Go
- Size: 2.87 MB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 6
-
Metadata Files:
- Readme: README.md
- License: license.txt
Awesome Lists containing this project
README
# Regex to struct library
[](https://golang.org/doc/devel/release.html)
[](https://github.com/fclairamb/restruct/releases/latest)
[](https://github.com/fclairamb/restruct/actions/workflows/build.yml)
[](https://codecov.io/gh/fclairamb/restruct)
[](https://goreportcard.com/report/fclairamb/restruct)
[](https://godoc.org/github.com/fclairamb/restruct)
## General idea
This is a very simple library that allows you to convert a regex into a struct. It's intended to be used for simple text parsing around
dummy bots.
The struct shall have a field for each capture group of the regex.
## Usage
This can be tested [on the playground](https://go.dev/play/p/beFzEua9vlE).
```golang
package main
import (
"fmt"
r "github.com/fclairamb/restruct"
)
func main() {
type Human struct {
Name string `restruct:"name"` // Specifying the field
Age int // No tag, "age" will be used
Height *int // A pointer will be set to nil if the capture group is empty
}
rs := &r.Restruct{
RegexToStructs: []*r.RegexToStruct{
{
ID: "age",
Regex: `^(?P\w+) is (?P\d+)( years old)?$`,
Struct: &Human{},
},
{
ID: "height",
Regex: `^(?P\w+) is (?P\d+) cm tall$`,
Struct: &Human{},
},
},
}
for _, input := range []string{"John is 178 cm tall", "John is 42 years old"} {
fmt.Println("input:", input)
m, _ := rs.MatchString(input)
if m == nil {
fmt.Printf(`No match for "%s"`, input)
continue
}
fmt.Println(" match ID:", m.ID)
h := m.Struct.(*Human)
fmt.Printf(" name = %v, age = %v", h.Name, h.Age)
if h.Height != nil {
fmt.Printf(", height = %v", *h.Height)
}
fmt.Printf("\n")
}
}
```
This will produce:
```
input: John is 178 cm tall
match ID: height
name = John, age = 0, height = 178
input: John is 42 years old
match ID: age
name = John, age = 42
```
## Benchmark
It's _not_ fast:
```text
go test -bench=. -benchmem
goos: darwin
goarch: arm64
pkg: github.com/fclairamb/restruct/test
BenchmarkSmallStruct
BenchmarkSmallStruct-8 2813796 406.5 ns/op 145 B/op 6 allocs/op
BenchmarkThreeRules-8 1869470 651.4 ns/op 145 B/op 6 allocs/op
BenchmarkBiggerStruct-8 2122315 564.2 ns/op 177 B/op 10 allocs/op
```