如何使用正则表达式替换数字?

时间:2011-07-15 05:48:39

标签: c# regex

我正在使用C#regex库来查找和替换一些文本。

我想更改以下内容:

1 - >一个

11 - >一个人

123 - >一二三

例如,这是替换&符号的代码:

        string pattern = "[&]";
        string replacement = " and ";
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(text, replacement);

修改 我在MSDN上找到了一些很好的.NET RegEx示例:

http://msdn.microsoft.com/en-us/library/kweb790z.aspx

1 个答案:

答案 0 :(得分:4)

由于你特意要求正则表达式,你可以做这样的事情

var digits = new Dictionary<string, string> { 
   { "0", "zero" },
   { "1", "one" },
   { "2", "two" },
   { "3", "three" },
   { "4", "four" },
   { "5", "five" },
   { "6", "six" },
   { "7", "seven" },
   { "8", "eight" },
   { "9", "nine" }
};

var text = "this is a text with some numbers like 123 and 456";

text = Regex.Replace(text, @"\d", x => digits[x.Value]);

会给你

this is a text with some numbers like onetwothree and fourfivesix