Regex replace by group index

paiv
Mon, 04 Aug 2025 16:57:41 +0000
General Usage

When doing string replace with regex, I want to know which capture group matched, so I can perform replacement specific to that group.

For example, if matched at word boundary, the letter should be replaced with X, and if followed by c, the letter should be replaced with _:

# "abac" => "Xb_c"
tr = ["X", "_"]
replace("abac", r"\b(\w)|(\w)(?=c)" => f)
f(s) = tr[1] # ?

Here f would be given the string "a" in both matches, and I have no indication of which group matched. Splitting replace into multiple runs is not possible, since the context for each match will change.

Currently I am working around this by providing custom method

Base._replace(io::IO, repl_s::_MyT, str, r, re::Base.RegexAndMatchData) = begin
    n = Base.PCRE.substring_length_bynumber(re.match_data, 1)
    ...

but I don’t feel at ease by patching internal methods.

Is there a better way? For reference, other languages would provide full Match object to f in this case.

6 posts - 3 participants