Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
DotNETFrameworkNotesForProfessionals.pdf
Скачиваний:
32
Добавлен:
20.05.2023
Размер:
1.82 Mб
Скачать

Chapter 15: Regular Expressions (System.Text.RegularExpressions)

Section 15.1: Check if pattern matches input

public bool Check()

{

string input = "Hello World!"; string pattern = @"H.ll. W.rld!";

// true

return Regex.IsMatch(input, pattern);

}

Section 15.2: Remove non alphanumeric characters from string

public string Remove()

{

string input = "Hello./!";

return Regex.Replace(input, "[^a-zA-Z0-9]", "");

}

Section 15.3: Passing Options

public bool Check()

{

string input = "Hello World!"; string pattern = @"H.ll. W.rld!";

// true

return Regex.IsMatch(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);

}

Section 15.4: Match into groups

public string Check()

{

string input = "Hello World!";

string pattern = @"H.ll. (?<Subject>W.rld)!"; Match match = Regex.Match(input, pattern);

// World

return match.Groups["Subject"].Value;

}

Section 15.5: Find all matches

Using

using System.Text.RegularExpressions;

Code

GoalKicker.com – .NET Framework Notes for Professionals

65

static void Main(string[] args)

{

string input = "Carrot Banana Apple Cherry Clementine Grape";

// Find words that start with uppercase 'C' string pattern = @"\bC\w*\b";

MatchCollection matches = Regex.Matches(input, pattern); foreach (Match m in matches)

Console.WriteLine(m.Value);

}

Output

Carrot

Cherry

Clementine

Section 15.6: Simple match and replace

public string Check()

{

string input = "Hello World!"; string pattern = @"W.rld";

// Hello Stack Overflow!

return Regex.Replace(input, pattern, "Stack Overflow");

}

GoalKicker.com – .NET Framework Notes for Professionals

66