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

add method to replace that takes a function RegexMatch -> String #41051

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ export
Rational,
Regex,
RegexMatch,
RegexReplacer,
Returns,
RoundFromZero,
RoundDown,
Expand Down
60 changes: 52 additions & 8 deletions base/regex.jl
Original file line number Diff line number Diff line change
Expand Up @@ -364,6 +364,17 @@ true
"""
function match end

function _create_match(str::Union{SubString{String}, String}, re::Regex, data::Ptr{Cvoid})
n = div(PCRE.ovec_length(data), 2) - 1
p = PCRE.ovec_ptr(data)
mat = SubString(str, unsafe_load(p, 1)+1, prevind(str, unsafe_load(p, 2)+1))
cap = Union{Nothing,SubString{String}}[unsafe_load(p,2i+1) == PCRE.UNSET ? nothing :
SubString(str, unsafe_load(p,2i+1)+1,
prevind(str, unsafe_load(p,2i+2)+1)) for i=1:n]
off = Int[ unsafe_load(p,2i+1)+1 for i=1:n ]
RegexMatch(mat, cap, unsafe_load(p,1)+1, off, re)
end

function match(re::Regex, str::Union{SubString{String}, String}, idx::Integer,
add_opts::UInt32=UInt32(0))
compile(re)
Expand All @@ -373,14 +384,7 @@ function match(re::Regex, str::Union{SubString{String}, String}, idx::Integer,
PCRE.free_match_data(data)
return nothing
end
n = div(PCRE.ovec_length(data), 2) - 1
p = PCRE.ovec_ptr(data)
mat = SubString(str, unsafe_load(p, 1)+1, prevind(str, unsafe_load(p, 2)+1))
cap = Union{Nothing,SubString{String}}[unsafe_load(p,2i+1) == PCRE.UNSET ? nothing :
SubString(str, unsafe_load(p,2i+1)+1,
prevind(str, unsafe_load(p,2i+2)+1)) for i=1:n]
off = Int[ unsafe_load(p,2i+1)+1 for i=1:n ]
result = RegexMatch(mat, cap, unsafe_load(p,1)+1, off, re)
result = _create_match(str, re, data)
PCRE.free_match_data(data)
return result
end
Expand Down Expand Up @@ -528,6 +532,8 @@ end
Stores the given string `substr` as a `SubstitutionString`, for use in regular expression
substitutions. Most commonly constructed using the [`@s_str`](@ref) macro.

See also [`RegexReplacer`](@ref).

```jldoctest
julia> SubstitutionString("Hello \\\\g<name>, it's \\\\1")
s"Hello \\g<name>, it's \\1"
Expand Down Expand Up @@ -564,6 +570,8 @@ Construct a substitution string, used for regular expression substitutions. Wit
string, sequences of the form `\\N` refer to the Nth capture group in the regex, and
`\\g<groupname>` refers to a named capture group with name `groupname`.

See also [`RegexReplacer`](@ref).

```jldoctest
julia> msg = "#Hello# from Julia";

Expand Down Expand Up @@ -668,6 +676,42 @@ function _replace(io, repl_s::SubstitutionString, str, r, re)
end
end

"""
RegexReplacer(f::Function)

Create a `RegexReplacer` that can be used to
[`replace`](@ref replace(::AbstractString, ::Pair))
[`Regex`](@ref)-matched text using the given function `f`
with access to the current match and capture groups.

`f` must be callable with a [`RegexMatch`](@ref) and return a [`print`](@ref)-able object.

See also [`SubstitutionString`](@ref), [`@s_str`](@ref).

# Examples
```jldoctest
julia> s = "ax ay az bx by bz";

julia> replace(s, r"([ab])([xy])" => RegexReplacer(match -> uppercase(match[1]) * match[2]))
"Ax Ay az Bx By bz"

julia> template = "the {animal} is {activity}";

julia> variables = Dict("animal" => "fox", "activity" => "running");

julia> replace(template, r"{(.*?)}" => RegexReplacer(match -> variables[match[1]]))
"the fox is running"
```
"""
struct RegexReplacer
f::Function
end

function _replace(io, repl::RegexReplacer, str, r, re::RegexAndMatchData)
match = _create_match(str, re.re, re.match_data)
print(io, repl.f(match))
end

struct RegexMatchIterator
regex::Regex
string::String
Expand Down
2 changes: 2 additions & 0 deletions base/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,8 @@ where `s` is the matched substring (when `pat` is a `AbstractPattern` or `Abstra
character (when `pat` is an `AbstractChar` or a collection of `AbstractChar`).
If `pat` is a regular expression and `r` is a [`SubstitutionString`](@ref), then capture group
references in `r` are replaced with the corresponding matched text.
If `pat` is a regular expression and `r` is a [`RegexReplacer`](@ref),
then the matched substring is replaced with `r.f(m)` where `m` is a [`RegexMatch`](@ref).
To remove instances of `pat` from `string`, set `r` to the empty `String` (`""`).

Multiple patterns can be specified, and they will be applied left-to-right
Expand Down
1 change: 1 addition & 0 deletions doc/src/base/strings.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ Base.match
Base.eachmatch
Base.RegexMatch
Base.keys(::RegexMatch)
Base.RegexReplacer
Base.isless(::AbstractString, ::AbstractString)
Base.:(==)(::AbstractString, ::AbstractString)
Base.cmp(::AbstractString, ::AbstractString)
Expand Down
10 changes: 10 additions & 0 deletions test/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,8 @@ end
# Issue 36953
@test replace("abc", "" => "_", count=1) == "_abc"

# test replace with a RegexReplacer
@test replace("ax ay bx by", r"([ab])([xy])" => RegexReplacer(m -> uppercase(m[1]) * m[2])) === "Ax Ay Bx By"
end

@testset "replace many" begin
Expand Down Expand Up @@ -482,6 +484,14 @@ end
@test_throws ErrorException("PCRE error: unknown substring") replace(s, r"q" => s"a\1b")
@test_throws ErrorException("Bad replacement string: pattern is not a Regex") replace(s, "q" => s"a\1b")
end

# test replace with a RegexReplacer
@test replace("ax ay bx by",
"ay" => "cy",
r"([ab])([xy])" => RegexReplacer(m -> uppercase(m[1]) * m[2])) === "Ax cy Bx By"
@test replace("ax ay bx by",
r"([a])([xy])" => RegexReplacer(m -> uppercase(m[1]) * m[2]),
r"([ab])([xy])" => RegexReplacer(m -> "<" * m[1] * ">" * m[2]), count=3) === "Ax Ay <b>x by"
end

@testset "chomp/chop" begin
Expand Down