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

Chapter 18: Regex Parsing

Name

Pattern

RegexOptions

[Optional]

Timeout [Optional]

Details

The string pattern that has to be used for the lookup. For more information: msdn

The common options in here are Singleline and Multiline. They are changing the behaviour of pattern-elements like the dot (.) which won't cover a NewLine (\n) in

Multiline-Mode but in SingleLine-Mode. Default behaviour: msdn

Where patterns are getting more complex the lookup can consume more time. This is the passed timeout for the lookup just as known from network-programming.

Section 18.1: Single match

using System.Text.RegularExpressions;

string pattern = ":(.*?):";

string lookup = "--:text in here:--";

// Instanciate your regex object and pass a pattern to it

Regex rgxLookup = new Regex(pattern, RegexOptions.Singleline, TimeSpan.FromSeconds(1));

//Get the match from your regex-object

Match mLookup = rgxLookup.Match(lookup);

//The group-index 0 always covers the full pattern.

//Matches inside parentheses will be accessed through the index 1 and above. string found = mLookup.Groups[1].Value;

Result:

found = "text in here"

Section 18.2: Multiple matches

using System.Text.RegularExpressions;

List<string> found = new List<string>(); string pattern = ":(.*?):";

string lookup = "--:text in here:--:another one:-:third one:---!123:fourth:";

// Instanciate your regex object and pass a pattern to it

Regex rgxLookup = new Regex(pattern, RegexOptions.Singleline, TimeSpan.FromSeconds(1)); MatchCollection mLookup = rgxLookup.Matches(lookup);

foreach(Match match in mLookup)

{

found.Add(match.Groups[1].Value);

}

Result:

found = new List<string>() { "text in here", "another one", "third one", "fourth" }

GoalKicker.com – C# Notes for Professionals

80