Skip to content

Commit

Permalink
deprecate replace(s::String, pat, r, n) to replace(s, pat=>r, count=n) (
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet authored Dec 22, 2017
1 parent 84b14ac commit da52b79
Show file tree
Hide file tree
Showing 29 changed files with 160 additions and 157 deletions.
5 changes: 3 additions & 2 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -632,8 +632,9 @@ Deprecated or removed

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

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

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

Expand Down
11 changes: 8 additions & 3 deletions base/deprecated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1346,14 +1346,19 @@ end
function replace(s::AbstractString, pat, f, n::Integer)
if n <= 0
depwarn(string("`replace(s, pat, r, count)` with `count <= 0` is deprecated, use ",
"`replace(s, pat, r, typemax(Int))` or `replace(s, pat, r)` instead"),
"`replace(s, pat=>r, count=typemax(Int))` or `replace(s, pat=>r)` instead"),
:replace)
replace(s, pat, f)
replace(s, pat=>f)
else
replace_new(String(s), pat, f, n)
depwarn(string("`replace(s, pat, r, count)` is deprecated, use ",
"`replace(s, pat=>r, count=count)`"),
:replace)
replace(String(s), pat=>f, count=n)
end
end

@deprecate replace(s::AbstractString, pat, f) replace(s, pat=>f)

# PR #22475
@deprecate ntuple(f, ::Type{Val{N}}) where {N} ntuple(f, Val(N))
@deprecate fill_to_length(t, val, ::Type{Val{N}}) where {N} fill_to_length(t, val, Val(N)) false
Expand Down
2 changes: 1 addition & 1 deletion base/libgit2/utils.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ Standardise the path string `path` to use POSIX separators.
"""
function posixpath end
if Sys.iswindows()
posixpath(path) = replace(path,'\\','/')
posixpath(path) = replace(path,'\\' => '/')
elseif Sys.isunix()
posixpath(path) = path
end
Expand Down
4 changes: 2 additions & 2 deletions base/markdown/GitHub/table.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function parserow(stream::IO)
row = split(line, r"(?<!\\)\|")
length(row) == 1 && return
isempty(row[1]) && popfirst!(row)
map!(x -> strip(replace(x, "\\|", "|")), row, row)
map!(x -> strip(replace(x, "\\|" => "|")), row, row)
isempty(row[end]) && pop!(row)
return row
end
Expand Down Expand Up @@ -104,7 +104,7 @@ _dash(width, align) =

function plain(io::IO, md::Table)
cells = mapmap(md.rows) do each
replace(plaininline(each), "|", "\\|")
replace(plaininline(each), "|" => "\\|")
end
padcells!(cells, md.align, len = length, min = 3)
for i = axes(cells,1)
Expand Down
2 changes: 1 addition & 1 deletion base/markdown/render/html.jl
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ for ch in "'`!\$%()=+{}[]"
end

function htmlesc(io::IO, s::AbstractString)
# s1 = replace(s, r"&(?!(\w+|\#\d+);)", "&amp;")
# s1 = replace(s, r"&(?!(\w+|\#\d+);)" => "&amp;")
for ch in s
print(io, get(_htmlescape_chars, ch, ch))
end
Expand Down
2 changes: 1 addition & 1 deletion base/markdown/render/rst.jl
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ end

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

rstescape(s) = replace(s, "\\", "\\\\")
rstescape(s) = replace(s, "\\" => "\\\\")

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

Expand Down
2 changes: 1 addition & 1 deletion base/markdown/render/terminal/formatting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ end
# Wrapping

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

words(s) = split(s, " ")
Expand Down
2 changes: 1 addition & 1 deletion base/markdown/render/terminal/render.jl
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ function terminline(io::IO, content::Vector)
end

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

function terminline(io::IO, md::Bold)
Expand Down
2 changes: 1 addition & 1 deletion base/methodshow.jl
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ function url(m::Method)
file = string(m.file)
line = m.line
line <= 0 || ismatch(r"In\[[0-9]+\]", file) && return ""
Sys.iswindows() && (file = replace(file, '\\', '/'))
Sys.iswindows() && (file = replace(file, '\\' => '/'))
if inbase(M)
if isempty(Base.GIT_VERSION_INFO.commit)
# this url will only work if we're on a tagged release
Expand Down
2 changes: 1 addition & 1 deletion base/pkg/reqs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ struct Requirement <: Line
system::Vector{AbstractString}

function Requirement(content::AbstractString)
fields = split(replace(content, r"#.*$", ""))
fields = split(replace(content, r"#.*$" => ""))
system = AbstractString[]
while !isempty(fields) && fields[1][1] == '@'
push!(system,popfirst!(fields)[2:end])
Expand Down
2 changes: 1 addition & 1 deletion base/process.jl
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ function show(io::IO, cmd::Cmd)
with_output_color(:underline, io) do io
print_shell_word(io, arg, shell_special)
end
end, '`', "\\`")
end, '`' => "\\`")
end, ' '))
print(io, '`')
print_env && (print(io, ","); show(io, cmd.env))
Expand Down
4 changes: 2 additions & 2 deletions base/repl/LineEdit.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1883,12 +1883,12 @@ function bracketed_paste(s; tabwidth=options(s).tabwidth)
ps = state(s, mode(s))
str = readuntil(ps.terminal, "\e[201~")
input = str[1:prevind(str, end-5)]
input = replace(input, '\r', '\n')
input = replace(input, '\r' => '\n')
if position(buffer(s)) == 0
indent = Base.indentation(input; tabwidth=tabwidth)[1]
input = Base.unindent(input, indent; tabwidth=tabwidth)
end
return replace(input, '\t', " "^tabwidth)
return replace(input, '\t' => " "^tabwidth)
end

function tab_should_complete(s)
Expand Down
6 changes: 3 additions & 3 deletions base/repl/REPL.jl
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ function add_history(hist::REPLHistoryProvider, s)
entry = """
# time: $(Libc.strftime("%Y-%m-%d %H:%M:%S %Z", time()))
# mode: $mode
$(replace(str, r"^"ms, "\t"))
$(replace(str, r"^"ms => "\t"))
"""
# TODO: write-lock history file
seekend(hist.history_file)
Expand Down Expand Up @@ -946,7 +946,7 @@ function setup_interface(
tail = lstrip(tail)
end
if isprompt_paste # remove indentation spaces corresponding to the prompt
tail = replace(tail, r"^ {7}"m, "") # 7: jl_prompt_len
tail = replace(tail, r"^ {7}"m => "") # 7: jl_prompt_len
end
LineEdit.replace_line(s, tail, true)
LineEdit.refresh_line(s)
Expand All @@ -956,7 +956,7 @@ function setup_interface(
line = strip(input[oldpos:prevind(input, pos)])
if !isempty(line)
if isprompt_paste # remove indentation spaces corresponding to the prompt
line = replace(line, r"^ {7}"m, "") # 7: jl_prompt_len
line = replace(line, r"^ {7}"m => "") # 7: jl_prompt_len
end
# put the line on the screen and history
LineEdit.replace_line(s, line)
Expand Down
8 changes: 4 additions & 4 deletions base/repl/REPLCompletions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ function complete_path(path::AbstractString, pos; use_envpath=false)
end
end

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

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

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

if inc_tag == :string &&
length(paths) == 1 && # Only close if there's a single choice,
!isdir(expanduser(replace(string[startpos:prevind(string, start(r))] * paths[1],
r"\\ ", " "))) && # except if it's a directory
r"\\ " => " "))) && # except if it's a directory
(length(string) <= pos ||
string[nextind(string,pos)] != '"') # or there's already a " at the cursor.
paths[1] *= "\""
Expand Down
2 changes: 1 addition & 1 deletion base/repl/latex_symbols.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const latex_strings = Set(values(Base.REPLCompletions.latex_symbols))
open(fname) do f
for L in eachline(f)
x = map(s -> rstrip(s, [' ','\t','\n']),
split(replace(L, r"[{}\"]+", "\t"), "\t"))
split(replace(L, r"[{}\"]+" => "\t"), "\t"))
c = Char(parse(Int, x[2], 16))
if (Base.is_id_char(c) || Base.isoperator(Symbol(c))) &&
string(c) ∉ latex_strings && !isascii(c)
Expand Down
6 changes: 3 additions & 3 deletions base/shell.jl
Original file line number Diff line number Diff line change
Expand Up @@ -222,11 +222,11 @@ function print_shell_escaped_posixly(io::IO, args::AbstractString...)
return true
end
if all(isword, arg)
have_single && (arg = replace(arg, '\'', "\\'"))
have_double && (arg = replace(arg, '"', "\\\""))
have_single && (arg = replace(arg, '\'' => "\\'"))
have_double && (arg = replace(arg, '"' => "\\\""))
print(io, arg)
else
print(io, '\'', replace(arg, '\'', "'\\''"), '\'')
print(io, '\'', replace(arg, '\'' => "'\\''"), '\'')
end
first = false
end
Expand Down
20 changes: 9 additions & 11 deletions base/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,8 @@ _replace(io, repl, str, r, pattern) = print(io, repl)
_replace(io, repl::Function, str, r, pattern) =
print(io, repl(SubString(str, first(r), last(r))))

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

"""
replace(s::AbstractString, pat, r, [count::Integer])
replace(s::AbstractString, pat=>r; [count::Integer])
Search for the given pattern `pat` in `s`, and replace each occurrence with `r`.
If `count` is provided, replace at most `count` occurrences.
As with [`search`](@ref), the second argument may be a
As with [`search`](@ref), `pat` may be a
single character, a vector or a set of characters, a string, or a regular expression. If `r`
is a function, each occurrence is replaced with `r(s)` where `s` is the matched substring.
If `pat` is a regular expression and `r` is a `SubstitutionString`, then capture group
Expand All @@ -420,20 +420,18 @@ To remove instances of `pat` from `string`, set `r` to the empty `String` (`""`)
# Examples
```jldoctest
julia> replace("Python is a programming language.", "Python", "Julia")
julia> replace("Python is a programming language.", "Python" => "Julia")
"Julia is a programming language."
julia> replace("The quick foxes run quickly.", "quick", "slow", 1)
julia> replace("The quick foxes run quickly.", "quick" => "slow", count=1)
"The slow foxes run quickly."
julia> replace("The quick foxes run quickly.", "quick", "", 1)
julia> replace("The quick foxes run quickly.", "quick" => "", count=1)
"The foxes run quickly."
```
"""
replace(s::AbstractString, pat, f) = replace_new(String(s), pat, f, typemax(Int))
# TODO: change this to the following when `replace` is removed from deprecated.jl:
# replace(s::AbstractString, pat, f, count::Integer=typemax(Int)) =
# replace(String(s), pat, f, count)
replace(s::AbstractString, pat_f::Pair; count=typemax(Int)) =
replace(String(s), pat_f, count=count)

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

Expand Down
2 changes: 1 addition & 1 deletion doc/src/stdlib/strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Base.searchindex
Base.rsearchindex
Base.contains(::AbstractString, ::AbstractString)
Base.reverse(::Union{String,SubString{String}})
Base.replace(s::AbstractString, pat, f)
Base.replace(s::AbstractString, ::Pair)
Base.split
Base.rsplit
Base.strip
Expand Down
4 changes: 2 additions & 2 deletions stdlib/Dates/src/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ function DateFormat(f::AbstractString, locale::DateLocale=ENGLISH)

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

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

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

if !isempty(prev)
letter, width = prev
Expand Down
6 changes: 3 additions & 3 deletions stdlib/DelimitedFiles/src/DelimitedFiles.jl
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ function store_cell(dlmstore::DLMStore{T}, row::Int, col::Int,

# fill data
if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos)
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"", "\"")
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"" => "\"")
fail = colval(unescaped, 1, endof(unescaped), cells, drow, col)
else
fail = colval(sbuff, startpos, endpos, cells, drow, col)
Expand All @@ -399,7 +399,7 @@ function store_cell(dlmstore::DLMStore{T}, row::Int, col::Int,
else
# fill header
if quoted && _chrinstr(sbuff, UInt8('"'), startpos, endpos)
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"", "\"")
unescaped = replace(SubString(sbuff, startpos, endpos), r"\"\"" => "\"")
colval(unescaped, 1, endof(unescaped), dlmstore.hdr, 1, col)
else
colval(sbuff, startpos, endpos, dlmstore.hdr, 1, col)
Expand Down Expand Up @@ -733,7 +733,7 @@ end
writedlm_cell(io::IO, elt::AbstractFloat, dlm, quotes) = print_shortest(io, elt)
function writedlm_cell(io::IO, elt::AbstractString, dlm::T, quotes::Bool) where T
if quotes && !isempty(elt) && (('"' in elt) || ('\n' in elt) || ((T <: Char) ? (dlm in elt) : contains(elt, dlm)))
print(io, '"', replace(elt, r"\"", "\"\""), '"')
print(io, '"', replace(elt, r"\"" => "\"\""), '"')
else
print(io, elt)
end
Expand Down
2 changes: 1 addition & 1 deletion test/libgit2.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2550,7 +2550,7 @@ mktempdir() do dir
try
# In some environments, namely Macs, the hostname "macbook.local" is bound
# to the external address while "macbook" is bound to the loopback address.
pushfirst!(hostnames, replace(gethostname(), r"\..*$", ""))
pushfirst!(hostnames, replace(gethostname(), r"\..*$" => ""))
end

loopback = ip"127.0.0.1"
Expand Down
2 changes: 1 addition & 1 deletion test/logging.jl
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ end
s = String(take!(io))
# Remove the small amount of color, as `Base.print_with_color` can't be
# simply controlled.
s = replace(s, r"^\e\[1m\e\[..m(.*)\e\[39m\e\[22m"m, s"\1")
s = replace(s, r"^\e\[1m\e\[..m(.*)\e\[39m\e\[22m"m => s"\1")
# println(s)
s
end
Expand Down
4 changes: 2 additions & 2 deletions test/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ Base.promote_rule(::Type{T19714}, ::Type{Int}) = T19714
end
@testset "function negation" begin
str = randstring(20)
@test filter(!Base.Unicode.isupper, str) == replace(str, r"[A-Z]", "")
@test filter(!Base.Unicode.islower, str) == replace(str, r"[a-z]", "")
@test filter(!Base.Unicode.isupper, str) == replace(str, r"[A-Z]" => "")
@test filter(!Base.Unicode.islower, str) == replace(str, r"[a-z]" => "")
end

# issue #19891
Expand Down
5 changes: 2 additions & 3 deletions test/perf/shootout/regex_dna.jl
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function regex_dna(infile="regexdna-input.txt")
seq = read(infile, String)
l1 = length(seq)

seq = replace(seq, r">.*\n|\n", "")
seq = replace(seq, r">.*\n|\n" => "")
l2 = length(seq)

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

for (u, v) in subs
seq = replace(seq, u, v)
seq = replace(seq, u => v)
end

# println()
# println(l1)
# println(l2)
# println(length(seq))
end

4 changes: 2 additions & 2 deletions test/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ let m = match(r"(?<a>.)(.)(?<b>.)", "xyz")
end

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

# Proper unicode handling
@test match(r"∀∀", "∀x∀∀∀").match == "∀∀"
2 changes: 1 addition & 1 deletion test/replcompletions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,7 @@ end
let path = tempdir(),
space_folder = randstring() * " α",
dir = joinpath(path, space_folder),
dir_space = replace(space_folder, " ", "\\ ")
dir_space = replace(space_folder, " " => "\\ ")

mkdir(dir)
cd(path) do
Expand Down
Loading

0 comments on commit da52b79

Please sign in to comment.