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

Inconsistent behaviour for replace #28967

Closed
getzze opened this issue Aug 30, 2018 · 7 comments
Closed

Inconsistent behaviour for replace #28967

getzze opened this issue Aug 30, 2018 · 7 comments

Comments

@getzze
Copy link
Contributor

getzze commented Aug 30, 2018

Julia Version 1.0.0

Steps to reproduce:

a = "1,2,3"
replace(a, "1"=>"0", "2"=>"1")
# MethodError: no method matching replace(::String, ::Pair{String,String}, ::Pair{String,String})

When acting on a String, replace argument is: replace(::AbstractString, pat=>r), where (quoting from the docs)

pat may be a single character, a vector or a set of characters, a string, or a regular expression

On the contrary, when acting on a collection (although Strings are collections): replace(collection, new_old::Pair...) with variable number of arguments.

replace for Strings should follow the same semantics as for collection (maybe also implementing the version taking a function as argument). But the fact that pat can be an array of characters is useful for removing several characters for example.

@nalimilan
Copy link
Member

Yes, the multiple-pair method is missing. #25732 fixes this.

@diegozea
Copy link
Contributor

#25732 hasn't been merged, so this inconsistency behaviour of replace between Strings and Vectors remains.

Related issue: #29849

@diegozea
Copy link
Contributor

This is a short alternative to replace("1,2,3", "1"=>"0", "2"=>"1"):

julia> reduce(replace, ("1"=>"0", "2"=>"1"), init="1,2,3")
"0,1,3"

@o314
Copy link
Contributor

o314 commented Dec 22, 2018

Hiccup.jl use the macrotools package to do this

htmlescape(s::AbstractString) =
    @> s replace("&" => "&amp;") replace("<" => "&lt;") replace(">" => "&gt;")

but i found it's very overkill there.

@o314
Copy link
Contributor

o314 commented Dec 22, 2018

That's simply works

Base.replace(s::String, oldnews::Pair...) = reduce(replace, oldnews, init=s)

using Test
@test Base.replace("a & b > c", "&"=>"&amp;",">"=>"&gt;") == "a &amp; b &gt; c"

@nalimilan
Copy link
Member

See #30457.

@laborg
Copy link
Contributor

laborg commented Feb 4, 2022

This has finally been implemented in #40484

@laborg laborg closed this as completed Feb 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants