Float / Scientific Number in GO
Match floating-point and scientific-notation numbers including `1.5`, `.25`, `1e10`, `-3.14E-2`.
Try it in the GO tester →Pattern
regexGO
[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)? (flags: g)Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?`)
input := `h = 6.626e-34, c = 3e8, alpha = .007`
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
[-+]? matches an optional sign. (?:\d+\.?\d*|\.\d+) matches the mantissa as either digits-with-optional-decimal or decimal-with-trailing-digits. (?:[eE][-+]?\d+)? matches the optional exponent. Covers most real-number literals you'll encounter in source or data.
Examples
Input
h = 6.626e-34, c = 3e8, alpha = .007Matches
6.626e-343e8.007
Input
Range -1.5 to +2.5Matches
-1.5+2.5
Input
no numbers hereNo match
—