Tom Gullen
Tom Gullen

Reputation: 61725

c# Regex match and replace using function

/// <summary>
/// Given HTML overlay for an image in the store, render it.
/// [p:n] renders as price for item ID n
/// </summary>
/// <returns>Rendered result</returns>
public static string RenderHTMLOverlay(string overlayHTML, int currencyID)
{
    const string pattern = "\\[p\\:(\\b\\d+\\b)\\]";
    overlayHTML = Regex.Replace(overlayHTML, pattern, FormatCurrency(GetItemPriceOnDate(DateTime.Now, currencyID, int.Parse("$1"))));

    return overlayHTML;
}

This doesn't work because $1 can't be passed as a parameter correctly to int.Parse.

Exception Details: System.FormatException: Input string was not in a correct format.

Does anyone know how I can work around this limitation?

Upvotes: 1

Views: 416

Answers (2)

Arithmomaniac
Arithmomaniac

Reputation: 4794

You can only use the $1 notation if the replacement argument is a string, so you ended up passing $1 as a literal string to the int.Parse method.

Instead, use the (String, String, MatchEvaluator) overload with an anonymous method:

Regex.Replace(overlayHTML, pattern, 
match => FormatCurrency(GetItemPriceOnDate(DateTime.Now, currencyID, int.Parse(match.Groups[1].Value)))
)

Upvotes: 3

GrayFox374
GrayFox374

Reputation: 1782

I'm not totally sure I understand you, so bear with me if I am off.

 Console.WriteLine(int.Parse("$1"));  //throws exception Input string was not in a correct format.

 Console.WriteLine(int.Parse("$1".Replace("$", "")));  //Result: 1

If Store.CommonFunctions.GetItemPriceOnDate returns a string, you should be good to go.

Upvotes: -1

Related Questions