Regex replace: Replace only (first) group of a match

Given this (TeX) string (with a newline at the end):
\fill[cardbackground, rounded corners=2pt] (0,0) rectangle (\cardwidth,\cardheight);

I am able to match with this regex:
~r/.*(cardbackground).*;\n/

How do I replace only the first group match (which is cardbackground in this case) using something like:
Regex.replace(~r/.*(cardbackground).*;\n/, source, "{RGB}{245,245,245}")

Looking at Regex — Elixir v1.18.4 is of not much help (to me).

What do I miss?

As you didn’t share any code, I have to ask whether you tried global: false?

If you only want to replace cardbackground, only match that:

Regex.replace(~r/cardbackground/, source, ...)

If you want to look for a pattern but not include it in the match, you can use a positive lookahead assertion:

Regex.replace(~r/cardbackground(?=.*;\n)/, source, ...)

This still only matches cardbackground alone, so that’s the only part that gets replaced. The assertion looks for ;\n at the end of the line.

2 Likes

Yes. Positive look ahead might work.

Reason for changing only a single group within a match is:
There might be a small chance that cardbackground can appear within another context more than one time and matching just this is not enough.

But I will be able to match the surrounding text using one or two lookaheads

Just a global: false might be not sufficient in this case.

Anyway: Thank you both for chiming in