US Currency (USD) in GO
Matches USD currency amounts with optional $ sign, thousands separators, and cents.
Try it in the GO tester →Pattern
regexGO
^\$?\d{1,3}(,\d{3})*(\.\d{2})?$Go (RE2) code
goGo
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`^\$?\d{1,3}(,\d{3})*(\.\d{2})?$`)
input := `$1,234.56`
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 dollar sign. `\d{1,3}(,\d{3})*` matches the integer part with optional comma-separated thousands. `(\.\d{2})?` optional cents.
Examples
Input
$1,234.56Matches
$1,234.56
Input
999Matches
999
Input
$1000000.00No match
—