balexandre
balexandre

Reputation: 75083

How to replace a string using the original matched value

I'm trying to Highlight a string by wrapping a <span class="highlight"></span> in the searched string.

made a simple Extension Method as:

public static string Highlight(this string source, string highlightString)
{
    var regex = new Regex(highlightString, RegexOptions.IgnoreCase);
    var r = regex.Replace(
                source, 
                "<span class=\"highlight\">" + highlightString + "</span>");

    return r;
}

works fine but what I really trying to do is apply the wrapping in the original match.

as is, if I search for trip I get the result of

<span class="highlight">trip</span> Nordic

and what I really want, is to have

<span class="highlight">Trip</span> Nordic

as the original string is Trip Nordic

how can I replace the original part of the string that it's matched and not the string I'm searching for?

the bugger is that regex has no property that tells me what was found (as original string), not even the position where it found the match...

Upvotes: 0

Views: 114

Answers (2)

Nyx
Nyx

Reputation: 425

regex.Replace(
            source, 
            "<span class=\"highlight\">$0</span>");

should work too.

$0 = group zero = whole match

Upvotes: 1

Alberto
Alberto

Reputation: 15941

If I understand correctly, you can use substitution:

public static string Highlight(this string source, string highlightString)
{
    var regex = new Regex(highlightString, RegexOptions.IgnoreCase);
    var r = regex.Replace(
            source, 
            "<span class=\"highlight\">$&</span>");
}

Output:

<span class="highlight">Trip</span> Nordic

Upvotes: 4

Related Questions