Go (RE2)

Credit Card Number in GO

Match 16-digit credit card numbers with optional spaces or hyphens between groups of 4.

Try it in the GO tester →

Pattern

regexGO
\b(?:\d{4}[\s\-]?){3}\d{4}\b   (flags: g)

Go (RE2) code

goGo
package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`\b(?:\d{4}[\s\-]?){3}\d{4}\b`)
	input := `4111 1111 1111 1111`
	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

Three groups of 4 digits with optional space/hyphen separators, followed by a final 4-digit group. Word boundaries prevent partial matches.

Examples

Input

4111 1111 1111 1111

Matches

  • 4111 1111 1111 1111

Input

4111-1111-1111-1111

Matches

  • 4111-1111-1111-1111

Input

4111111111111111

Matches

  • 4111111111111111

Same pattern, other engines

← Back to Credit Card Number overview (all engines)