编辑
2025-09-24
C#
00

目录

使用 $ 符号进行简单的替换
使用 $ 符号进行动态模板替换
使用 $ 符号进行复杂的模板替换

正则表达式是一种强大的文本匹配和处理工具,在C#中得到了广泛的应用。除了用于匹配和提取文本信息外,正则表达式还可以进行替换和模板操作,而 $ 符号在这一过程中扮演着重要的角色。

使用 $ 符号进行简单的替换

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "Hello, $name! Today is $day."; string pattern = @"\$name"; string result = Regex.Replace(input, pattern, "Alice"); pattern = @"\$day"; result = Regex.Replace(result, pattern, "Monday"); Console.WriteLine(result); // 输出:Hello, Alice! Today is Monday. } }

image.png

在上面的例子中,我们使用了 $ 符号来进行简单的替换操作。首先,我们使用正则表达式模式 \$name 匹配到 $name,然后使用 Regex.Replace 方法将其替换为具体的值 "Alice"。同样的方法也适用于 $day

使用 $ 符号进行动态模板替换

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string template = "Dear $name, your total amount is $amount."; string result = template; result = Regex.Replace(result, @"\$name", "Bob"); result = Regex.Replace(result, @"\$amount", "100"); Console.WriteLine(result); // 输出:Dear Bob, your total amount is 100. } }

image.png

在这个例子中,我们使用正则表达式和 $ 符号进行动态模板替换。我们首先将模板字符串赋给 result,然后使用 Regex.Replace 方法依次替换 $name$amount

使用 $ 符号进行复杂的模板替换

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "The price is $price, and the discount is $discount."; string result = Regex.Replace(input, @"\$(\w+)", m => { switch (m.Groups[1].Value) { case "price": return "100"; case "discount": return "10"; default: return m.Value; } }); Console.WriteLine(result); // 输出:The price is 100, and the discount is 10. } }

image.png

在这个例子中,我们使用了正则表达式和 $ 符号进行复杂的模板替换。我们使用了正则表达式 \$(\w+) 匹配到 $price$discount,然后通过回调函数对匹配到的内容进行动态替换。

通过以上例子,我们可以看到在C#中使用 $ 符号进行正则表达式的替换和模板操作是非常灵活和强大的,可以帮助我们处理各种复杂的文本替换需求。希望以上例子可以帮助你更好地理解和应用这一技术。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!