Skip to content

Commit

Permalink
Further simplify regex
Browse files Browse the repository at this point in the history
Reduces fix time by about 30% in the test suite.

```
goos: darwin
goarch: amd64
pkg: github.com/automattic/go-search-replace
BenchmarkFix-4                      1000000          2074 ns/op         216 B/op           7 allocs/op
BenchmarkSimpleReplace-4            2000000           605 ns/op         480 B/op           7 allocs/op
BenchmarkSerializedReplace-4         500000          3589 ns/op         696 B/op          14 allocs/op
PASS
ok      github.com/automattic/go-search-replace    5.786s
```

```
goos: darwin
goarch: amd64
pkg: github.com/automattic/go-search-replace
BenchmarkFix-4                      1000000          1484 ns/op          88 B/op           4 allocs/op
BenchmarkSimpleReplace-4            2000000           624 ns/op         480 B/op           7 allocs/op
BenchmarkSerializedReplace-4         500000          3085 ns/op         568 B/op          11 allocs/op
PASS
ok      github.com/automattic/go-search-replace    4.976s
```
  • Loading branch information
joshbetz committed Jan 30, 2018
1 parent 0998f62 commit a4b0eea
Showing 1 changed file with 4 additions and 4 deletions.
8 changes: 4 additions & 4 deletions search-replace.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (

const (
searchRe = `s:\d+:\\\".*?\\\";`
replaceRe = `(?:s:)(?:\d+:)(\\\")(.*?)(\\\";)`
replaceRe = `s:\d+:\\\"(.*?)\\\";`

badInputRe = `\w:\d+:`
inputRe = `^[A-Za-z0-9_\-\.:/]+$`
Expand Down Expand Up @@ -128,14 +128,14 @@ func replaceAndFix(line string, replacements map[string]string) string {
func fix(match string) string {
parts := replace.FindStringSubmatch(match)

if len(parts) < 3 {
if len(parts) != 2 {
// This looks wrong, don't touch anything
return match
}

// Get string length - number of escaped characters and avoid double counting escaped \
length := len(parts[2]) - (strings.Count(parts[2], `\`) - strings.Count(parts[2], `\\`))
return fmt.Sprintf("s:%d:%s%s%s", length, parts[1], parts[2], parts[3])
length := len(parts[1]) - (strings.Count(parts[1], `\`) - strings.Count(parts[1], `\\`))
return fmt.Sprintf("s:%d:\\\"%s\\\";", length, parts[1])
}

func validInput(in string, length int) bool {
Expand Down

0 comments on commit a4b0eea

Please sign in to comment.