Elliot Pixel
Elliot Pixel

Reputation: 27

Replace first occurrence in Regex.Replace

    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?

Upvotes: 0

Views: 555

Answers (1)

Elliot Pixel
Elliot Pixel

Reputation: 27

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);
    }

Upvotes: 1

Related Questions