Skip to content

Instantly share code, notes, and snippets.

@crhntr
Last active September 14, 2023 20:51
Show Gist options
  • Save crhntr/b2345902e225c3efdac61f902029fbca to your computer and use it in GitHub Desktop.
Save crhntr/b2345902e225c3efdac61f902029fbca to your computer and use it in GitHub Desktop.
My answer to a slack question: "Anyone know of a package for parsing semi-structured queries of the style title:something description:"something else" visibility:public?"
package main
import (
"fmt"
"strconv"
"strings"
"text/scanner"
)
func main() {
src := `title:something description:"something else" visibility:public`
var s scanner.Scanner
s.Init(strings.NewReader(src))
const (
keyState = iota
sepState
valState
)
state := keyState
result := make(map[string]string)
var key string
for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
switch state {
case keyState:
key = s.TokenText()
state = sepState
case sepState:
state = valState
case valState:
val := s.TokenText()
if v, err := strconv.Unquote(val); err == nil {
val = v
}
result[key] = val
state = keyState
key = ""
}
}
fmt.Printf("%+v\n", result)
}
@crhntr
Copy link
Author

crhntr commented Sep 14, 2023

I wrote this circa 2019 in response to a slack message from a co-worker.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment