在 C# 中使用正则表达式时,字符类是构建模式的基础之一。字符类允许你定义一组字符,正则表达式引擎将匹配这组字符中的任何一个字符。本文将详细介绍 C# 中的正则表达式字符类,并通过多个示例展示其用法。
字符类通过方括号 []
定义,可以包含单个字符、字符范围或者字符组合。以下是一些常用的字符类:
[abc]
: 匹配 'a'、'b' 或 'c'[^abc]
: 匹配除了 'a'、'b'、'c' 之外的任意字符[a-z]
: 匹配任意小写字母[A-Z]
: 匹配任意大写字母[0-9]
: 匹配任意数字\d
: 匹配任意数字,等同于 [0-9]
\w
: 匹配任意字母、数字或下划线,等同于 [a-zA-Z0-9_]
\s
: 匹配任意空白字符,如空格、制表符或换行符[abc]
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "[abc]";
string input = "Fantasy and science fiction";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: a Found: a Found: c Found: c
[^abc]
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "[^abc]";
string input = "Escape the island";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: E
Found: s
Found: p
Found: e
Found: // 空格也被匹配
Found: t
Found: h
Found: e
Found: // 空格也被匹配
Found: i
Found: s
Found: l
Found: n
Found: d
[a-z]
和 [A-Z]
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "[a-zA-Z]";
string input = "Regex101: The Tutorial";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: R Found: e Found: g Found: e Found: x Found: T Found: h Found: e Found: T Found: u Found: t Found: o Found: r Found: i Found: a Found: l
\d
和 [0-9]
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = @"\d";
string input = "The year is 2023.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: 2
Found: 0
Found: 2
Found: 3
\w
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = @"\w";
string input = "Password: abc123_XYZ!";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine($"Found: {match.Value}");
}
}
}
输出:
C#Found: P
Found: a
Found: s
Found: s
Found: w
Found: o
Found: r
Found: d
Found: a
Found: b
Found: c
Found: 1
Found: 2
Found: 3
Found: _
Found: X
Found: Y
Found: Z
\s
C#using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = @"\s";
string input = "Whitespace\tcharacters\ninclude spaces.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine("Found a whitespace character.");
}
}
}
输出:
C#Found a whitespace character. Found a whitespace character. Found a whitespace character.
字符类在 C# 中的正则表达式中非常有用,它们提供了一种灵活的方式来匹配特定的字符集合。通过使用字符类,你可以创建更加精确和复杂的匹配模式来处理字符串数据。掌握不同类型的字符类对于编写有效的正则表达式至关重要。以上示例应该能够帮助你开始在自己的 C# 项目中使用字符类进行模式匹配。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!