From dc3c5a8325eb2f425906b6419806862de84416ef Mon Sep 17 00:00:00 2001 From: Adam Scarr Date: Wed, 9 Aug 2017 21:41:57 +1000 Subject: Add a regex parser --- parser.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) (limited to 'parser.go') diff --git a/parser.go b/parser.go index 7b45004..a23cef5 100644 --- a/parser.go +++ b/parser.go @@ -3,6 +3,7 @@ package goparsify import ( "errors" "fmt" + "regexp" "strings" "unicode/utf8" ) @@ -102,6 +103,20 @@ func Run(parser Parserish, input string) (result interface{}, err error) { return ret.Result, nil } +// Regex returns a match if the regex successfully matches +func Regex(pattern string) Parser { + re := regexp.MustCompile("^" + pattern) + return NewParser(pattern, func(ps *State) Result { + ps.AutoWS() + if match := re.FindString(ps.Get()); match != "" { + ps.Advance(len(match)) + return Result{Token: match} + } + ps.ErrorHere(pattern) + return Result{} + }) +} + // Exact will fully match the exact string supplied, or error. The match will be stored in .Token func Exact(match string) Parser { if len(match) == 1 { -- cgit v1.2.3