c#正则表达式匹配和替换使用函数 [英] c# Regex match and replace using function

查看:31
本文介绍了c#正则表达式匹配和替换使用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这不起作用,因为 $1 无法作为参数正确传递给 int.Parse.

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?

推荐答案

如果 replacement 参数是字符串,你只能使用 $1 表示法,所以你结束了将 $1 作为文字字符串传递给 int.Parse 方法.

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.

改为使用(String, String, MatchEvaluator) 使用匿名方法重载:

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

这篇关于c#正则表达式匹配和替换使用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆