Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix for 31456 -- replace with optional matching group fails when there is no match #31493

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion base/pcre.jl
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,11 @@ function substring_length_bynumber(match_data, number)
s = RefValue{Csize_t}()
rc = ccall((:pcre2_substring_length_bynumber_8, PCRE_LIB), Cint,
(Ptr{Cvoid}, UInt32, Ref{Csize_t}), match_data, number, s)
rc < 0 && error("PCRE error: $(err_message(rc))")
if rc < 0
# PCRE2_ERROR_UNSET see https://code.woboq.org/qt5/qtbase/src/3rdparty/pcre2/src/pcre2_substring.c.html
rc == -55 && return 0
Comment on lines +159 to +160
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
# PCRE2_ERROR_UNSET see https://code.woboq.org/qt5/qtbase/src/3rdparty/pcre2/src/pcre2_substring.c.html
rc == -55 && return 0
rc == ERROR_UNSET && return 0

error("PCRE error: $(err_message(rc))")
end
convert(Int, s[])
end

Expand Down
3 changes: 3 additions & 0 deletions base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,9 @@ replace_err(repl) = error("Bad replacement string: $repl")

function _write_capture(io, re, group)
len = PCRE.substring_length_bynumber(re.match_data, group)
# in the case of an optional group that doesn't match, len == 0
# e.g. replace("The fox.", r"fox(es)?" => s"bus\1")
len == 0 && return
ensureroom(io, len+1)
PCRE.substring_copy_bynumber(re.match_data, group,
pointer(io.data, io.ptr), len+1)
Expand Down
5 changes: 5 additions & 0 deletions test/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,11 @@ end
# Issue 13332
@test replace("abc", 'b' => 2.1) == "a2.1c"

# Issue 31456
@test replace("The fox.", r"fox(es)?" => s"bus\1") == "The bus."
@test replace("The foxes.", r"fox(es)?" => s"bus\1") == "The buses."
@test replace("The quick fox quickly.", r"(quick)?\sfox(es)?\s(run)?" => s"\1 bus\2 \3") == "The quick bus quickly."

# test replace with a count for String and GenericString
# check that replace is a no-op if count==0
for s in ["aaa", Test.GenericString("aaa")]
Expand Down