我如何使用正则表达式替换数字
本文关键字:替换 数字 正则表达式 何使用 | 更新日期: 2023-09-27 18:02:14
我正在使用c# regex库来做一些文本查找和替换。
我想更改以下内容:
1 -> 1
11 -> 1 - 1
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既然你特别要求一个正则表达式,你可以这样做
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