JSON Number (Strict) in GO
Match JSON-spec numbers — disallows leading zeros (no `01`), allows decimals and exponents.
Try it in the GO tester →Pattern
regexGO
-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)? (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][-+]?\d+)?`)
input := `values: 0, 42, -3.14, 6.022e23`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
How the pattern works
-? optional sign. (?:0|[1-9]\d*) the integer part: either a single zero or a non-zero digit followed by any digits (no leading zeros allowed per RFC 8259). (?:\.\d+)? optional decimal part. (?:[eE][-+]?\d+)? optional exponent. Strict per JSON spec — won't match `01` or `1.` (which are valid JS but not JSON).
Examples
Input
values: 0, 42, -3.14, 6.022e23Matches
042-3.146.022e23
Input
0.5 vs invalid 01Matches
0.501
Input
no numbersNo match
—