0
    string MatchFormat(string subject, string sample, string color)
    {
        if (string.IsNullOrEmpty(sample))
            return subject;

        sample = Regex.Escape(sample);
        return Regex.Replace(subject, sample, m => $"<color={color}>{m.Value}</color>");
    }

I'd like to only replace the first found occurrence of sample with m => $"<color={color}>{m.Value}</color>". How can I do this?

Ňɏssa Pøngjǣrdenlarp
  • 38,411
  • 12
  • 59
  • 178
  • 1
    Does this answer your question? [Regex.Replace: replace only first one found](https://stackoverflow.com/questions/6372065/regex-replace-replace-only-first-one-found). There is an overload of this method that will take an integer indicating the max occurrences to replace. [regularexpressions](https://learn.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex.replace?view=net-7.0#system-text-regularexpressions-regex-replace(system-string-system-text-regularexpressions-matchevaluator-system-int32-system-int32)) – Ryan Wilson Oct 07 '22 at 15:03
  • 1
    The best way to share your solution is not to add it to your question, but to add it as an answer. – Eric J. Oct 07 '22 at 15:31
  • I propose a framing challenge. If you find yourself using Regex to manipulate XML as text you're usually going about it wrong. You should always try and work with structured and parse-able data by parsing it. It's more reliable, can be validated, and is often faster. – Logarr Oct 07 '22 at 15:45

1 Answers1

1

SOLUTION:

    string MatchFormat(string subject, string sample, string color)
    {
        if (string.IsNullOrEmpty(sample))
            return subject;

        sample = Regex.Escape(sample);
        var r = new Regex(sample);
        return r.Replace(subject, m => $"<color={color}>{m.Value}</color>", 1);
    }
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 11 '22 at 16:08