Книга: C# 2008 Programmer

Searching for a Match

Searching for a Match

To use the RegEx class, first you need to import the System.Text.RegularExpressions namespace:

using System.Text.RegularExpressions;

The following statements shows how you can create an instance of the RegEx class, specify the pattern to search for, and match it against a string:

string s = "This is a string";
Regex r = new Regex("string");
if (r.IsMatch(s)) {
 Console.WriteLine("Matches.");
}

In this example, the Regex class takes in a string constructor, which is the pattern you are searching for. In this case, you are searching for the word "string" and it is matched against the s string variable. The IsMatch() method returns True if there is a match (that is, the string s contains the word "string").

To find the exact position of the text "string" in the variable, you can use the Match() method of the RegEx class. It returns a Match object that you can use to get the position of the text that matches the search pattern using the Index property:

string s = "This is a string";
Regex r = new Regex("string");
if (r.IsMatch(s)) {
 Console.WriteLine("Matches.");
}
Match m = r.Match(s);
if (m.Success) {
 Console.WriteLine("Match found at " + m.Index); //---Match found at 10---
}

What if you have multiple matches in a string? In this case, you can use the Matches() method of the RegEx class. This method returns a MatchCollection object, and you can iteratively loop through it to obtain the index positions of each individual match:

string s = "This is a string and a long string indeed";
Regex r = new Regex("string");
MatchCollection mc = r.Matches(s);
foreach (Match m1 in mc) {
 Console.WriteLine("Match found at " + m1.Index);
 //---Match found at 10---
 //---Match found at 28---
}

Оглавление книги

Оглавление статьи/книги

Генерация: 1.137. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз