344.C# 中的正则表达式:字符匹配、字面字符、特殊字符和转义序列
在 C# 中,正则表达式是通过 System.Text.RegularExpressions 命名空间中的 Regex 类实现的。正则表达式允许你以灵活和高效的方式进行字符串搜索、替换和解析。本文将介绍在 C# 中使用正则表达式时的字符匹配、字面字符、特殊字符和转义序列,并提供示例。
字符匹配
字符匹配是正则表达式的核心,它允许你定义应该匹配的文本模式。
字面字符
字面字符是正则表达式中直接匹配其自身的字符。它们不具备特殊含义,只代表字符本身。
示例
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = "cat";
string input = "The cat sat on the mat.";
Match match = Regex.Match(input, pattern);
if (match.Success)
{
Console.WriteLine(#34;Found '{match.Value}' at position {match.Index}");
}
}
}
输出:
Found 'cat' at position 4
特殊字符
特殊字符在正则表达式中具有特定的含义,用于构建复杂的匹配模式。
常用特殊字符
- . :匹配任意单个字符(换行符除外)。
- \d:匹配任意数字。
- \w:匹配任意字母、数字或下划线。
- \s:匹配任意空白字符(空格、制表符等)。
- * :匹配前一个字符零次或多次。
- + :匹配前一个字符一次或多次。
- ? :匹配前一个字符零次或一次。
- {n}:匹配前一个字符 n 次。
- | :逻辑或操作符。
- ():捕获组。
示例
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string pattern = @"\d+";
string input = "Room 101 or Room 202?";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(#34;Found number: {match.Value}");
}
}
}
输出:
Found number: 101
Found number: 202
转义序列
在正则表达式中,如果你想要匹配特殊字符的字面值,你需要使用转义序列。在 C# 中,转义序列是通过在特殊字符前面放置一个反斜杠 \ 来创建的。
示例
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
// 匹配点号 (.)
string pattern = @"\.";
string input = "End of sentence. Start of sentence.";
foreach (Match match in Regex.Matches(input, pattern))
{
Console.WriteLine(#34;Found period at position {match.Index}");
}
// 匹配圆括号 ()
pattern = @"\(\d+\)";
input = "The answer is (42).";
Match matchParens = Regex.Match(input, pattern);
if (matchParens.Success)
{
Console.WriteLine(#34;Found: {matchParens.Value}");
}
}
}
输出:
Found period at position 15
Found period at position 32
Found: (42)
总结
在 C# 中使用正则表达式时,理解字面字符、特殊字符和转义序列的概念至关重要。字面字符直接匹配文本,特殊字符用于构建复杂的匹配模式,而转义序列则用于匹配特殊字符本身。通过组合这些元素,你可以构建出能够解决实际问题的强大正则表达式。