正则表达式10-替换
好吧,到目前为止,貌似只有搜索的,那我要是想替换原始字符串中的某个部分怎么办呢?嗯,本章就是为了解决这个问题存在的。
要使用替换功能,请使用微软提供的 Regex.Replace() 方法,记得引用 using System.Text.RegularExpressions 命名空间
原始字符串:$16.32 12.19 £16.29 €18.29 €18,29
正则表达式:\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*
const string input = "$16.32 12.19 £16.29 €18.29 €18,29"; const string pattern = @"\p{Sc}*(\s?\d+[.,]?\d*)\p{Sc}*"; const string replacement = "$1"; string result = Regex.Replace(input, pattern, replacement); Console.WriteLine(result);
程序输出结果:16.32 12.19 16.29 18.29 18,29
解释:正则表达式是一个分组表达式,它搜索带或者不带钱币符号的数字,找到该数字后,将其编号为 1 组;替换表达式的意思就是要将匹配的结果替换成 1 组,也就是纯数字,这样就去掉了钱币符号。
上面的例子我们可以改写一下,不用分组编号,而用分组名称来实现。
string input = "$16.32 12.19 £16.29 €18.29 €18,29"; string pattern = @"\p{Sc}*(?<amount>\s?\d+[.,]?\d*)\p{Sc}*"; string replacement = "${amount}"; string result = Regex.Replace(input, pattern, replacement); Console.WriteLine(result);
程序输出结果:16.32 12.19 16.29 18.29 18,29
这里就不一一介绍了,查查 MSDN 吧。都不难,就是利用了分组搜索而已。