Skip to content

Commit 6e17cb2

Browse files
committed
deprecate replace(s::String, pat, r, n) to replace(s, pat=>r, count=n)
1 parent 6c94bd8 commit 6e17cb2

29 files changed

+160
-157
lines changed

NEWS.md

+3-2
Original file line numberDiff line numberDiff line change
@@ -632,8 +632,9 @@ Deprecated or removed
632632

633633
* `?` can no longer be used as an identifier name ([#22712])
634634

635-
* The method `replace(s::AbstractString, pat, r, count)` with `count <= 0` is deprecated
636-
in favor of `replace(s::AbstractString, pat, r, typemax(Int))` ([#22325]).
635+
* The method `replace(s::AbstractString, pat, r, [count])` is deprecated
636+
in favor of `replace(s::AbstractString, pat => r; [count])` ([#25165]).
637+
Moreover, `count` cannot be negative anymore (use `typemax(Int)` instead ([#22325]).
637638

638639
* `read(io, type, dims)` is deprecated to `read!(io, Array{type}(dims))` ([#21450]).
639640

base/deprecated.jl

+8-3
Original file line numberDiff line numberDiff line change
@@ -1346,14 +1346,19 @@ end
13461346
function replace(s::AbstractString, pat, f, n::Integer)
13471347
if n <= 0
13481348
depwarn(string("`replace(s, pat, r, count)` with `count <= 0` is deprecated, use ",
1349-
"`replace(s, pat, r, typemax(Int))` or `replace(s, pat, r)` instead"),
1349+
"`replace(s, pat=>r, count=typemax(Int))` or `replace(s, pat=>r)` instead"),
13501350
:replace)
1351-
replace(s, pat, f)
1351+
replace(s, pat=>f)
13521352
else
1353-
replace_new(String(s), pat, f, n)
1353+
depwarn(string("`replace(s, pat, r, count)` is deprecated, use ",
1354+
"`replace(s, pat=>r, count=count)`"),
1355+
:replace)
1356+
replace(String(s), pat=>f, count=n)
13541357
end
13551358
end
13561359

1360+
@deprecate replace(s::AbstractString, pat, f) replace(s, pat=>f)
1361+
13571362
# PR #22475
13581363
@deprecate ntuple(f, ::Type{Val{N}}) where {N} ntuple(f, Val(N))
13591364
@deprecate fill_to_length(t, val, ::Type{Val{N}}) where {N} fill_to_length(t, val, Val(N)) false

base/libgit2/utils.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ Standardise the path string `path` to use POSIX separators.
8383
"""
8484
function posixpath end
8585
if Sys.iswindows()
86-
posixpath(path) = replace(path,'\\','/')
86+
posixpath(path) = replace(path,'\\' => '/')
8787
elseif Sys.isunix()
8888
posixpath(path) = path
8989
end

base/markdown/GitHub/table.jl

+2-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ function parserow(stream::IO)
1111
row = split(line, r"(?<!\\)\|")
1212
length(row) == 1 && return
1313
isempty(row[1]) && popfirst!(row)
14-
map!(x -> strip(replace(x, "\\|", "|")), row, row)
14+
map!(x -> strip(replace(x, "\\|" => "|")), row, row)
1515
isempty(row[end]) && pop!(row)
1616
return row
1717
end
@@ -104,7 +104,7 @@ _dash(width, align) =
104104

105105
function plain(io::IO, md::Table)
106106
cells = mapmap(md.rows) do each
107-
replace(plaininline(each), "|", "\\|")
107+
replace(plaininline(each), "|" => "\\|")
108108
end
109109
padcells!(cells, md.align, len = length, min = 3)
110110
for i = axes(cells,1)

base/markdown/render/html.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ for ch in "'`!\$%()=+{}[]"
3131
end
3232

3333
function htmlesc(io::IO, s::AbstractString)
34-
# s1 = replace(s, r"&(?!(\w+|\#\d+);)", "&amp;")
34+
# s1 = replace(s, r"&(?!(\w+|\#\d+);)" => "&amp;")
3535
for ch in s
3636
print(io, get(_htmlescape_chars, ch, ch))
3737
end

base/markdown/render/rst.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ end
124124

125125
rstinline(io::IO, f::Footnote) = print(io, "[", f.id, "]_")
126126

127-
rstescape(s) = replace(s, "\\", "\\\\")
127+
rstescape(s) = replace(s, "\\" => "\\\\")
128128

129129
rstinline(io::IO, s::AbstractString) = print(io, rstescape(s))
130130

base/markdown/render/terminal/formatting.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ end
5151
# Wrapping
5252

5353
function ansi_length(s)
54-
replace(s, r"\e\[[0-9]+m", "") |> length
54+
replace(s, r"\e\[[0-9]+m" => "") |> length
5555
end
5656

5757
words(s) = split(s, " ")

base/markdown/render/terminal/render.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ function terminline(io::IO, content::Vector)
114114
end
115115

116116
function terminline(io::IO, md::AbstractString)
117-
print(io, replace(md, r"[\s\t\n]+", " "))
117+
print(io, replace(md, r"[\s\t\n]+" => " "))
118118
end
119119

120120
function terminline(io::IO, md::Bold)

base/methodshow.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ function url(m::Method)
203203
file = string(m.file)
204204
line = m.line
205205
line <= 0 || ismatch(r"In\[[0-9]+\]", file) && return ""
206-
Sys.iswindows() && (file = replace(file, '\\', '/'))
206+
Sys.iswindows() && (file = replace(file, '\\' => '/'))
207207
if inbase(M)
208208
if isempty(Base.GIT_VERSION_INFO.commit)
209209
# this url will only work if we're on a tagged release

base/pkg/reqs.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ struct Requirement <: Line
1919
system::Vector{AbstractString}
2020

2121
function Requirement(content::AbstractString)
22-
fields = split(replace(content, r"#.*$", ""))
22+
fields = split(replace(content, r"#.*$" => ""))
2323
system = AbstractString[]
2424
while !isempty(fields) && fields[1][1] == '@'
2525
push!(system,popfirst!(fields)[2:end])

base/process.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ function show(io::IO, cmd::Cmd)
107107
with_output_color(:underline, io) do io
108108
print_shell_word(io, arg, shell_special)
109109
end
110-
end, '`', "\\`")
110+
end, '`' => "\\`")
111111
end, ' '))
112112
print(io, '`')
113113
print_env && (print(io, ","); show(io, cmd.env))

base/repl/LineEdit.jl

+2-2
Original file line numberDiff line numberDiff line change
@@ -1883,12 +1883,12 @@ function bracketed_paste(s; tabwidth=options(s).tabwidth)
18831883
ps = state(s, mode(s))
18841884
str = readuntil(ps.terminal, "\e[201~")
18851885
input = str[1:prevind(str, end-5)]
1886-
input = replace(input, '\r', '\n')
1886+
input = replace(input, '\r' => '\n')
18871887
if position(buffer(s)) == 0
18881888
indent = Base.indentation(input; tabwidth=tabwidth)[1]
18891889
input = Base.unindent(input, indent; tabwidth=tabwidth)
18901890
end
1891-
return replace(input, '\t', " "^tabwidth)
1891+
return replace(input, '\t' => " "^tabwidth)
18921892
end
18931893

18941894
function tab_should_complete(s)

base/repl/REPL.jl

+3-3
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ function add_history(hist::REPLHistoryProvider, s)
450450
entry = """
451451
# time: $(Libc.strftime("%Y-%m-%d %H:%M:%S %Z", time()))
452452
# mode: $mode
453-
$(replace(str, r"^"ms, "\t"))
453+
$(replace(str, r"^"ms => "\t"))
454454
"""
455455
# TODO: write-lock history file
456456
seekend(hist.history_file)
@@ -946,7 +946,7 @@ function setup_interface(
946946
tail = lstrip(tail)
947947
end
948948
if isprompt_paste # remove indentation spaces corresponding to the prompt
949-
tail = replace(tail, r"^ {7}"m, "") # 7: jl_prompt_len
949+
tail = replace(tail, r"^ {7}"m => "") # 7: jl_prompt_len
950950
end
951951
LineEdit.replace_line(s, tail, true)
952952
LineEdit.refresh_line(s)
@@ -956,7 +956,7 @@ function setup_interface(
956956
line = strip(input[oldpos:prevind(input, pos)])
957957
if !isempty(line)
958958
if isprompt_paste # remove indentation spaces corresponding to the prompt
959-
line = replace(line, r"^ {7}"m, "") # 7: jl_prompt_len
959+
line = replace(line, r"^ {7}"m => "") # 7: jl_prompt_len
960960
end
961961
# put the line on the screen and history
962962
LineEdit.replace_line(s, line)

base/repl/REPLCompletions.jl

+4-4
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ function complete_path(path::AbstractString, pos; use_envpath=false)
192192
end
193193
end
194194

195-
matchList = String[replace(s, r"\s", "\\ ") for s in matches]
195+
matchList = String[replace(s, r"\s" => "\\ ") for s in matches]
196196
startpos = pos - endof(prefix) + 1 - length(matchall(r" ", prefix))
197197
# The pos - endof(prefix) + 1 is correct due to `endof(prefix)-endof(prefix)==0`,
198198
# hence we need to add one to get the first index. This is also correct when considering
@@ -503,15 +503,15 @@ function completions(string, pos)
503503
startpos = nextind(partial, reverseind(partial, m.offset))
504504
r = startpos:pos
505505

506-
expanded = complete_expanduser(replace(string[r], r"\\ ", " "), r)
506+
expanded = complete_expanduser(replace(string[r], r"\\ " => " "), r)
507507
expanded[3] && return expanded # If user expansion available, return it
508508

509-
paths, r, success = complete_path(replace(string[r], r"\\ ", " "), pos)
509+
paths, r, success = complete_path(replace(string[r], r"\\ " => " "), pos)
510510

511511
if inc_tag == :string &&
512512
length(paths) == 1 && # Only close if there's a single choice,
513513
!isdir(expanduser(replace(string[startpos:prevind(string, start(r))] * paths[1],
514-
r"\\ ", " "))) && # except if it's a directory
514+
r"\\ " => " "))) && # except if it's a directory
515515
(length(string) <= pos ||
516516
string[nextind(string,pos)] != '"') # or there's already a " at the cursor.
517517
paths[1] *= "\""

base/repl/latex_symbols.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ const latex_strings = Set(values(Base.REPLCompletions.latex_symbols))
5353
open(fname) do f
5454
for L in eachline(f)
5555
x = map(s -> rstrip(s, [' ','\t','\n']),
56-
split(replace(L, r"[{}\"]+", "\t"), "\t"))
56+
split(replace(L, r"[{}\"]+" => "\t"), "\t"))
5757
c = Char(parse(Int, x[2], 16))
5858
if (Base.is_id_char(c) || Base.isoperator(Symbol(c))) &&
5959
string(c) ∉ latex_strings && !isascii(c)

base/shell.jl

+3-3
Original file line numberDiff line numberDiff line change
@@ -222,11 +222,11 @@ function print_shell_escaped_posixly(io::IO, args::AbstractString...)
222222
return true
223223
end
224224
if all(isword, arg)
225-
have_single && (arg = replace(arg, '\'', "\\'"))
226-
have_double && (arg = replace(arg, '"', "\\\""))
225+
have_single && (arg = replace(arg, '\'' => "\\'"))
226+
have_double && (arg = replace(arg, '"' => "\\\""))
227227
print(io, arg)
228228
else
229-
print(io, '\'', replace(arg, '\'', "'\\''"), '\'')
229+
print(io, '\'', replace(arg, '\'' => "'\\''"), '\'')
230230
end
231231
first = false
232232
end

base/strings/util.jl

+9-11
Original file line numberDiff line numberDiff line change
@@ -373,8 +373,8 @@ _replace(io, repl, str, r, pattern) = print(io, repl)
373373
_replace(io, repl::Function, str, r, pattern) =
374374
print(io, repl(SubString(str, first(r), last(r))))
375375

376-
# TODO: rename to `replace` when `replace` is removed from deprecated.jl
377-
function replace_new(str::String, pattern, repl, count::Integer)
376+
function replace(str::String, pat_repl::Pair; count::Integer=typemax(Int))
377+
pattern, repl = pat_repl
378378
count == 0 && return str
379379
count < 0 && throw(DomainError(count, "`count` must be non-negative."))
380380
n = 1
@@ -407,11 +407,11 @@ function replace_new(str::String, pattern, repl, count::Integer)
407407
end
408408

409409
"""
410-
replace(s::AbstractString, pat, r, [count::Integer])
410+
replace(s::AbstractString, pat=>r; [count::Integer])
411411
412412
Search for the given pattern `pat` in `s`, and replace each occurrence with `r`.
413413
If `count` is provided, replace at most `count` occurrences.
414-
As with [`search`](@ref), the second argument may be a
414+
As with [`search`](@ref), `pat` may be a
415415
single character, a vector or a set of characters, a string, or a regular expression. If `r`
416416
is a function, each occurrence is replaced with `r(s)` where `s` is the matched substring.
417417
If `pat` is a regular expression and `r` is a `SubstitutionString`, then capture group
@@ -420,20 +420,18 @@ To remove instances of `pat` from `string`, set `r` to the empty `String` (`""`)
420420
421421
# Examples
422422
```jldoctest
423-
julia> replace("Python is a programming language.", "Python", "Julia")
423+
julia> replace("Python is a programming language.", "Python" => "Julia")
424424
"Julia is a programming language."
425425
426-
julia> replace("The quick foxes run quickly.", "quick", "slow", 1)
426+
julia> replace("The quick foxes run quickly.", "quick" => "slow", count=1)
427427
"The slow foxes run quickly."
428428
429-
julia> replace("The quick foxes run quickly.", "quick", "", 1)
429+
julia> replace("The quick foxes run quickly.", "quick" => "", count=1)
430430
"The foxes run quickly."
431431
```
432432
"""
433-
replace(s::AbstractString, pat, f) = replace_new(String(s), pat, f, typemax(Int))
434-
# TODO: change this to the following when `replace` is removed from deprecated.jl:
435-
# replace(s::AbstractString, pat, f, count::Integer=typemax(Int)) =
436-
# replace(String(s), pat, f, count)
433+
replace(s::AbstractString, pat_f::Pair; count=typemax(Int)) =
434+
replace(String(s), pat_f, count=count)
437435

438436
# TODO: allow transform as the first argument to replace?
439437

doc/src/stdlib/strings.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ Base.searchindex
3838
Base.rsearchindex
3939
Base.contains(::AbstractString, ::AbstractString)
4040
Base.reverse(::Union{String,SubString{String}})
41-
Base.replace(s::AbstractString, pat, f)
41+
Base.replace(s::AbstractString, ::Pair)
4242
Base.split
4343
Base.rsplit
4444
Base.strip

stdlib/Dates/src/io.jl

+2-2
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ function DateFormat(f::AbstractString, locale::DateLocale=ENGLISH)
328328

329329
letters = String(collect(keys(CONVERSION_SPECIFIERS)))
330330
for m in eachmatch(Regex("(?<!\\\\)([\\Q$letters\\E])\\1*"), f)
331-
tran = replace(f[prev_offset:prevind(f, m.offset)], r"\\(.)", s"\1")
331+
tran = replace(f[prev_offset:prevind(f, m.offset)], r"\\(.)" => s"\1")
332332

333333
if !isempty(prev)
334334
letter, width = prev
@@ -348,7 +348,7 @@ function DateFormat(f::AbstractString, locale::DateLocale=ENGLISH)
348348
prev_offset = m.offset + width
349349
end
350350

351-
tran = replace(f[prev_offset:endof(f)], r"\\(.)", s"\1")
351+
tran = replace(f[prev_offset:endof(f)], r"\\(.)" => s"\1")
352352

353353
if !isempty(prev)
354354
letter, width = prev

stdlib/DelimitedFiles/src/DelimitedFiles.jl

+3-3
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ function store_cell(dlmstore::DLMStore{T}, row::Int, col::Int,
380380

381381
# fill data
382382
if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos)
383-
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"", "\"")
383+
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"" => "\"")
384384
fail = colval(unescaped, 1, endof(unescaped), cells, drow, col)
385385
else
386386
fail = colval(sbuff, startpos, endpos, cells, drow, col)
@@ -399,7 +399,7 @@ function store_cell(dlmstore::DLMStore{T}, row::Int, col::Int,
399399
else
400400
# fill header
401401
if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos)
402-
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"", "\"")
402+
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"" => "\"")
403403
colval(unescaped, 1, endof(unescaped), dlmstore.hdr, 1, col)
404404
else
405405
colval(sbuff, startpos, endpos, dlmstore.hdr, 1, col)
@@ -733,7 +733,7 @@ end
733733
writedlm_cell(io::IO, elt::AbstractFloat, dlm, quotes) = print_shortest(io, elt)
734734
function writedlm_cell(io::IO, elt::AbstractString, dlm::T, quotes::Bool) where T
735735
if quotes && !isempty(elt) && (('"' in elt) || ('\n' in elt) || ((T <: Char) ? (dlm in elt) : contains(elt, dlm)))
736-
print(io, '"', replace(elt, r"\"", "\"\""), '"')
736+
print(io, '"', replace(elt, r"\"" => "\"\""), '"')
737737
else
738738
print(io, elt)
739739
end

test/libgit2.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -2550,7 +2550,7 @@ mktempdir() do dir
25502550
try
25512551
# In some environments, namely Macs, the hostname "macbook.local" is bound
25522552
# to the external address while "macbook" is bound to the loopback address.
2553-
pushfirst!(hostnames, replace(gethostname(), r"\..*$", ""))
2553+
pushfirst!(hostnames, replace(gethostname(), r"\..*$" => ""))
25542554
end
25552555

25562556
loopback = ip"127.0.0.1"

test/logging.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ end
241241
s = String(take!(io))
242242
# Remove the small amount of color, as `Base.print_with_color` can't be
243243
# simply controlled.
244-
s = replace(s, r"^\e\[1m\e\[..m(.*)\e\[39m\e\[22m"m, s"\1")
244+
s = replace(s, r"^\e\[1m\e\[..m(.*)\e\[39m\e\[22m"m => s"\1")
245245
# println(s)
246246
s
247247
end

test/operators.jl

+2-2
Original file line numberDiff line numberDiff line change
@@ -110,8 +110,8 @@ Base.promote_rule(::Type{T19714}, ::Type{Int}) = T19714
110110
end
111111
@testset "function negation" begin
112112
str = randstring(20)
113-
@test filter(!Base.Unicode.isupper, str) == replace(str, r"[A-Z]", "")
114-
@test filter(!Base.Unicode.islower, str) == replace(str, r"[a-z]", "")
113+
@test filter(!Base.Unicode.isupper, str) == replace(str, r"[A-Z]" => "")
114+
@test filter(!Base.Unicode.islower, str) == replace(str, r"[a-z]" => "")
115115
end
116116

117117
# issue #19891

test/perf/shootout/regex_dna.jl

+2-3
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ function regex_dna(infile="regexdna-input.txt")
3636
seq = read(infile, String)
3737
l1 = length(seq)
3838

39-
seq = replace(seq, r">.*\n|\n", "")
39+
seq = replace(seq, r">.*\n|\n" => "")
4040
l2 = length(seq)
4141

4242
for v in variants
@@ -48,12 +48,11 @@ function regex_dna(infile="regexdna-input.txt")
4848
end
4949

5050
for (u, v) in subs
51-
seq = replace(seq, u, v)
51+
seq = replace(seq, u => v)
5252
end
5353

5454
# println()
5555
# println(l1)
5656
# println(l2)
5757
# println(length(seq))
5858
end
59-

test/regex.jl

+2-2
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,8 @@ let m = match(r"(?<a>.)(.)(?<b>.)", "xyz")
4545
end
4646

4747
# Backcapture reference in substitution string
48-
@test replace("abcde", r"(..)(?P<byname>d)", s"\g<byname>xy\\\1") == "adxy\\bce"
49-
@test_throws ErrorException replace("a", r"(?P<x>)", s"\g<y>")
48+
@test replace("abcde", r"(..)(?P<byname>d)" => s"\g<byname>xy\\\1") == "adxy\\bce"
49+
@test_throws ErrorException replace("a", r"(?P<x>)" => s"\g<y>")
5050

5151
# Proper unicode handling
5252
@test match(r"∀∀", "∀x∀∀∀").match == "∀∀"

test/replcompletions.jl

+1-1
Original file line numberDiff line numberDiff line change
@@ -704,7 +704,7 @@ end
704704
let path = tempdir(),
705705
space_folder = randstring() * " α",
706706
dir = joinpath(path, space_folder),
707-
dir_space = replace(space_folder, " ", "\\ ")
707+
dir_space = replace(space_folder, " " => "\\ ")
708708

709709
mkdir(dir)
710710
cd(path) do

0 commit comments

Comments
 (0)