Skip to content

Commit 4de47b2

Browse files
tlienartjohanmon
authored andcommitted
regex: remove error when accessing an unset group (JuliaLang#40391)
closes JuliaLang#31456
1 parent 956f36e commit 4de47b2

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

base/pcre.jl

+4-1
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,10 @@ function substring_length_bynumber(match_data, number)
228228
s = RefValue{Csize_t}()
229229
rc = ccall((:pcre2_substring_length_bynumber_8, PCRE_LIB), Cint,
230230
(Ptr{Cvoid}, Cint, Ref{Csize_t}), match_data, number, s)
231-
rc < 0 && error("PCRE error: $(err_message(rc))")
231+
if rc < 0
232+
rc == ERROR_UNSET && return 0
233+
error("PCRE error: $(err_message(rc))")
234+
end
232235
return Int(s[])
233236
end
234237

base/regex.jl

+2
Original file line numberDiff line numberDiff line change
@@ -528,6 +528,8 @@ replace_err(repl) = error("Bad replacement string: $repl")
528528

529529
function _write_capture(io, re::RegexAndMatchData, group)
530530
len = PCRE.substring_length_bynumber(re.match_data, group)
531+
# in the case of an optional group that doesn't match, len == 0
532+
len == 0 && return
531533
ensureroom(io, len+1)
532534
PCRE.substring_copy_bynumber(re.match_data, group,
533535
pointer(io.data, io.ptr), len+1)

test/strings/util.jl

+5
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,11 @@ end
275275
# Issue 13332
276276
@test replace("abc", 'b' => 2.1) == "a2.1c"
277277

278+
# Issue 31456
279+
@test replace("The fox.", r"fox(es)?" => s"bus\1") == "The bus."
280+
@test replace("The foxes.", r"fox(es)?" => s"bus\1") == "The buses."
281+
@test replace("The quick fox quickly.", r"(quick)?\sfox(es)?\s(run)?" => s"\1 bus\2 \3") == "The quick bus quickly."
282+
278283
# test replace with a count for String and GenericString
279284
# check that replace is a no-op if count==0
280285
for s in ["aaa", Test.GenericString("aaa")]

0 commit comments

Comments
 (0)