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?

3
  • 1
    Does this answer your question? 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 Commented Oct 7, 2022 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. Commented Oct 7, 2022 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. Commented Oct 7, 2022 at 15:45

1 Answer 1

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.