C# 正則表達(dá)式進階:模式修飾符
在C#中,正則表達(dá)式不僅可以用于簡單的文本匹配,還可以通過模式修飾符進行更加靈活和高級的匹配操作。其中,不區(qū)分大小寫和多行模式是兩個常用的模式修飾符,它們可以幫助我們處理各種復(fù)雜的匹配需求。
不區(qū)分大小寫模式(IgnoreCase)
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
}
}
圖片
在上面的例子中,我們使用了 RegexOptions.IgnoreCase 模式修飾符來實現(xiàn)不區(qū)分大小寫的匹配。即使正則表達(dá)式中的模式是小寫的 "hello",由于使用了 IgnoreCase 修飾符,它也能匹配到輸入字符串中的 "Hello"。
多行模式(Multiline)
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string input = "Line 1\nLine 2\nLine 3";
string pattern = "^Line";
Regex regex = new Regex(pattern, RegexOptions.Multiline);
MatchCollection matches = regex.Matches(input);
foreach (Match match in matches) {
Console.WriteLine(match.Value); // 輸出:Line
}
}
}
圖片
在這個例子中,我們使用了 RegexOptions.Multiline 模式修飾符來實現(xiàn)多行模式的匹配。正則表達(dá)式 ^Line 匹配以 "Line" 開頭的文本行,由于使用了 Multiline 修飾符,它可以匹配到輸入字符串中的每一行開頭的 "Line"。
通過以上例子,我們可以看到在C#中使用模式修飾符可以幫助我們處理各種復(fù)雜的匹配需求,包括不區(qū)分大小寫和多行模式等。希望以上例子可以幫助你更好地理解和應(yīng)用正則表達(dá)式的模式修飾符。