Skip to content

Commit

Permalink
Merge pull request #174 from matiasinsaurralde/regex-optimization
Browse files Browse the repository at this point in the history
Re-use compiled regular expressions when using the validator
  • Loading branch information
wadearnold authored May 7, 2018
2 parents 326785c + 223cdaa commit 0d2f7aa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
11 changes: 11 additions & 0 deletions fileHeader_internal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,17 @@ func TestMockFileHeader(t *testing.T) {

// TestParseFileHeader parses a known File Header Record string.
func TestParseFileHeader(t *testing.T) {
parseFileHeader(t)
}

func BenchmarkParseFileHeader(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
parseFileHeader(b)
}
}

func parseFileHeader(t testing.TB) {
var line = "101 076401251 0764012510807291511A094101achdestname companyname "
r := NewReader(strings.NewReader(line))
r.line = line
Expand Down
9 changes: 7 additions & 2 deletions validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@ import (
"strconv"
)

var (
upperAlphanumericRegex = regexp.MustCompile(`[^ A-Z0-9!"#$%&'()*+,-.\\/:;<>=?@\[\]^_{}|~]+`)
alphanumericRegex = regexp.MustCompile(`[^ \w!"#$%&'()*+,-.\\/:;<>=?@\[\]^_{}|~]+`)
)

// validator is common validation and formating of golang types to ach type strings
type validator struct{}

Expand Down Expand Up @@ -241,15 +246,15 @@ func (v *validator) isOriginatorStatusCode(code int) error {

// isUpperAlphanumeric checks if string only contains ASCII alphanumeric upper case characters
func (v *validator) isUpperAlphanumeric(s string) error {
if regexp.MustCompile(`[^ A-Z0-9!"#$%&'()*+,-.\\/:;<>=?@\[\]^_{}|~]+`).MatchString(s) {
if upperAlphanumericRegex.MatchString(s) {
return errors.New(msgUpperAlpha)
}
return nil
}

// isAlphanumeric checks if a string only contains ASCII alphanumeric characters
func (v *validator) isAlphanumeric(s string) error {
if regexp.MustCompile(`[^ \w!"#$%&'()*+,-.\\/:;<>=?@\[\]^_{}|~]+`).MatchString(s) {
if alphanumericRegex.MatchString(s) {
// ^[ A-Za-z0-9_@./#&+-]*$/
return errors.New(msgAlphanumeric)
}
Expand Down

0 comments on commit 0d2f7aa

Please sign in to comment.