正则表达式是用来匹配和处理文本的一种表达式语言。在C#中,可以使用System.Text.RegularExpressions命名空间下的类来进行正则表达式的处理。以下列出了一些常见的正则表达式的用法及示例:
1. 匹配数字:
使用\d来匹配数字,$表示末尾。
Regex.IsMatch("1234", @"^\d+$"); // true
Regex.IsMatch("a123", @"^\d+$"); // false
2. 匹配字母:
使用\w来匹配字母,$表示末尾,也可以使用[a-zA-Z]表示匹配字母。
Regex.IsMatch("hello", @"^\w+$"); // true
Regex.IsMatch("hello123", @"^\w+$"); // true
Regex.IsMatch("123hello", @"^\w+$"); // false
3. 匹配手机号:
使用正则表达式来匹配11位数字的手机号。
Regex.IsMatch("13812345678", @"^1[3-9][0-9]{9}$"); // true
Regex.IsMatch("11012345678", @"^1[3-9][0-9]{9}$"); // false
4. 匹配电子邮箱:
使用正则表达式来匹配电子邮箱格式。
Regex.IsMatch("abc@test.com", @"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+$"); // true
Regex.IsMatch("test", @"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+$"); // false
5. 匹配IP地址:
使用正则表达式来匹配IP地址格式。
Regex.IsMatch("192.168.1.1", @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // true
Regex.IsMatch("192.168.1", @"^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); // false
6. 匹配URL:
使用正则表达式来匹配URL格式。
Regex.IsMatch("http://www.test.com", @"^((ht|f)tps?):\/\/[^\s\/$.?#].[^\s]*$"); // true
Regex.IsMatch("www.test.com", @"^((ht|f)tps?):\/\/[^\s\/$.?#].[^\s]*$"); // false
7. 匹配日期:
使用正则表达式来匹配日期格式。
Regex.IsMatch("2021-04-01", @"^(\d{4})-(\d{2})-(\d{2})$"); // true
Regex.IsMatch("04-01-2021", @"^(\d{4})-(\d{2})-(\d{2})$"); // false
以上是一些常见的正则表达式的用法,但正则表达式的应用场景非常广泛,所以需要根据实际情况灵活运用。