Skip to content

Commit

Permalink
fix infinite loop when matching empty string in gsub
Browse files Browse the repository at this point in the history
  • Loading branch information
fstab committed Apr 2, 2019
1 parent 65e17cb commit be3cf96
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
16 changes: 11 additions & 5 deletions oniguruma/gsub.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,18 @@ func (regex *Regex) Gsub(input, replacement string) (string, error) {
end: searchResult.endPos(),
replacement: createReplacementString(searchResult, tokens),
})
offset = searchResult.endPos()
newOffset := searchResult.endPos()
searchResult.Free()
if offset == len(input) {
// If the regular expression matches an empty string, like .*
// we need to break here to avoid an infinite loop.
break
if newOffset == offset {
// We matched an empty string, for example with a regex like .* or .*?
// Either we are at the end of the input, then we quit
if offset == len(input) {
break
}
// Or we are not at the end of the input, then we continue with the next character.
offset++
} else {
offset = newOffset
}
}
err = assertNotOverlapping(replacements) // should never happen, but keep it for debugging
Expand Down
5 changes: 4 additions & 1 deletion oniguruma/gsub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,10 @@ func TestGsub(t *testing.T) {
{input: "", regex: ".", replacement: "*", expectedResult: ""},

// matches empty string
{input: "abc", regex: ".*", replacement: ".", expectedResult: "."},
// The following is the same behavior as Ruby's puts "abc".gsub(/.*/, ".")
{input: "abc", regex: ".*", replacement: ".", expectedResult: ".."},
// The following is the same behavior as Ruby's puts "abc".gsub(/.*?/, ".")
{input: "abc", regex: ".*?", replacement: ".", expectedResult: ".a.b.c."},
} {
r, err := Compile(data.regex)
if err != nil {
Expand Down

0 comments on commit be3cf96

Please sign in to comment.