Skip to content

Commit

Permalink
add method to replace that takes a function RegexMatch -> String
Browse files Browse the repository at this point in the history
  • Loading branch information
epithet committed Jun 1, 2021
1 parent 4a8572f commit 4c540ad
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
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
29 changes: 21 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::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 @@ -662,6 +666,15 @@ function _replace(io, repl_s::SubstitutionString, str, r, re::RegexAndMatchData)
end
end

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 test/strings/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,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 "chomp/chop" begin
Expand Down

0 comments on commit 4c540ad

Please sign in to comment.