Skip to content

Instantly share code, notes, and snippets.

@captncraig
Created August 26, 2015 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save captncraig/e295fbfd343fd4cd4e4f to your computer and use it in GitHub Desktop.
Save captncraig/e295fbfd343fd4cd4e4f to your computer and use it in GitHub Desktop.
ReadUntilRegex
func ReadUntilRegex(r io.Reader, regex string) (string, error) {
accumulated := []byte{}
reg, err := regexp.Compile(regex)
if err != nil {
return "", nil
}
for {
buf := make([]byte, 16*1024)
n, err := r.Read(buf)
if err != nil && err != io.EOF {
return "", err
}
accumulated = append(accumulated, buf[:n]...)
if err == io.EOF {
return string(accumulated), err
}
if reg.Match(accumulated) {
return string(accumulated), nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment