编辑
2025-09-24
C#
00

在C#中,Regex 类提供了 Split 方法来进行正则表达式的字符串分割操作。通过这个方法,我们可以对输入字符串进行灵活的分割处理。

使用场景

Split 方法适用于需要根据特定模式将字符串分割成多个部分的情况。比如,根据逗号分割字符串、根据空格分割句子等操作。

示例

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "apple,orange,banana,grape"; string pattern = ","; Regex regex = new Regex(pattern); string[] result = regex.Split(input); foreach (string s in result) { Console.WriteLine(s); // 输出:apple, orange, banana, grape } } }
编辑
2025-09-24
C#
00

在C#中,Regex 类提供了 Replace 方法来进行正则表达式的替换操作。通过这个方法,我们可以对输入字符串进行灵活的替换处理。

使用场景

Replace 方法适用于需要对文本中的特定模式进行替换的情况。比如,替换文本中的特定单词、格式化日期、清理特殊字符等操作。

示例

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "The color of the car is red."; string pattern = "red"; string replacement = "blue"; Regex regex = new Regex(pattern); string result = regex.Replace(input, replacement); Console.WriteLine(result); // 输出:The color of the car is blue. } }
编辑
2025-09-24
C#
00

在C#中,Regex 类提供了多种方法来进行正则表达式的匹配操作,包括 Match 方法和 Matches 方法。通过这些方法,我们可以对输入字符串进行灵活的匹配和处理。

Match 方法

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "Hello, world! This is a test."; string pattern = @"\b\w{5}\b"; // 匹配5个字母的单词 Regex regex = new Regex(pattern); Match match = regex.Match(input); if (match.Success) { Console.WriteLine(match.Value); // 输出:Hello } } }
编辑
2025-09-24
C#
00

在C#中,正则表达式不仅可以用于简单的文本匹配,还可以通过模式修饰符进行更加灵活和高级的匹配操作。其中,不区分大小写和多行模式是两个常用的模式修饰符,它们可以帮助我们处理各种复杂的匹配需求。

不区分大小写模式(IgnoreCase)

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string input = "Hello, world!"; string pattern = "hello"; Regex regex = new Regex(pattern, RegexOptions.IgnoreCase); bool isMatch = regex.IsMatch(input); Console.WriteLine(isMatch); // 输出:True } }
编辑
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. } }