编辑
2025-09-24
C#
00

正则表达式是一种强大的文本匹配工具,广泛应用于表单验证、日志文件解析和文本数据清洗等场景。通过合理地使用正则表达式,我们可以实现对文本数据的有效处理和验证。

邮箱地址验证

在表单验证中,常常需要对用户输入的邮箱地址进行验证,以确保其格式正确。以下是一个简单的示例:

C#
using System; using System.Text.RegularExpressions; class Program { static void Main() { string email = "example@example.com"; string pattern = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"; Regex regex = new Regex(pattern); bool isValid = regex.IsMatch(email); Console.WriteLine(isValid); // 输出:True } }
编辑
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 } }