Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Beginning Regular Expressions 2005.pdf
Скачиваний:
95
Добавлен:
17.08.2013
Размер:
25.42 Mб
Скачать

C# and Regular Expressions

Some basic display text is assigned to the Text property of textBox2:

this.textBox2.Text = “The string contained the following elements:” +

Environment.NewLine + Environment.NewLine;

Then a foreach loop is used to add the value of each string in the splitResults array to the value of the Text property of textBox2. Each element of the array is displayed on a separate line in the text box, due to the Environment.Newline:

foreach (string stringElement in splitResults)

this.textBox2.Text += stringElement + Environment.NewLine;

Using the Static Methods of the Regex Class

Several of the Regex class methods can be used as statics without your having to instantiate an instance of the Regex class.

Each of the following sections assumes that the following directive is in the code:

using System.Text.RegularExpressions;

The IsMatch() Method as a Static

Two overloads are available for the IsMatch() method:

public static bool Regex.IsMatch(string inputString, string pattern);

and:

public static bool Regex.IsMatch(string inputString, string pattern, RegexOptions

options);

The Match() Method as a Static

Two overloads are available for the Match() method as a static:

public static Match Match(string inputString, string pattern);

and:

public static Match Match(string inputString, string pattern, RegexOptions

options);

The Matches() Method as a Static

Two overloads are available for the Matches() method as a static:

public static MatchCollection Matches(string inputString, string pattern);

and:

public static MatchCollection Matches(string inputString, string pattern,

RegexOptions options);

531

Chapter 22

The Replace() Method as a Static

Two overloads are available for the Replace() method as a static:

public static string Regex.Replace(string inputString, string pattern, string

replacementString);

and:

public static string Regex.Replace(string inputString, string pattern, string

replacementString, RegexOptions options);

The Split() Method as a Static

Two overloads are available for the Split() method as a static:

public static string[] Regex.Split(string inputString, string pattern);

and:

public static string[] Regex.Split(string inputString, string pattern, RegexOptions

options);

The Match and Matches Classes

The Match class contains a single match. The MatchCollection class contains a collection of matches.

The Match Class

The Match class has no public constructor. Therefore, it must be accessed from another class. For example, this can be done using the Regex class’s Match() method.

A Match object has a Groups property. Every Match object has at least one group. The Match object is equivalent to Match.Groups[0], because the zeroth group contains the entire match.

The Match class has the properties described in the following table.

Property

Description

 

 

Captures

Gets a collection of captures captured by a capturing group. There

 

may be zero or more captures in a match.

Empty

Returned if an attempted match fails.

Groups

Gets a collection of groups that make up the match regular expres-

 

sion. Assuming that there is a match, there is at least one group in the

 

collection.

Index

The position in the string at which the first character of a successful

 

match is located.

 

 

532

 

 

C# and Regular Expressions

 

 

 

 

 

 

 

Property

Description

 

 

 

 

Length

The length of the matched substring.

 

Success

A value indicating whether or not the match was successful.

 

Value

The matched substring.

 

 

 

The Match object has the methods described in the following table. Not all are directly relevant to the use of regular expressions.

Method

Description

 

 

Equals

Determines whether two objects are equal

GetHashCode

Gets a hash code

GetType

Gets the type of the current object instance

NextMatch

Finds the next match in the test string, if such a match exists

Result

Contains the value after replacement

Synchronized

Returns a Match object that can be shared among threads

ToString

Gets the matched substring from the test string

 

 

The NextMatch() method can be used together with the Match() method to iterate through several matches in a test string.

Try It Out

Using the Match() and NextMatch() Methods

1.Open Visual Studio 2003, create a new project using the Windows Application template, and name the new project MatchNextMatchDemo.

2.Drag a label onto the form, and change its Text property to Demo of the Match() and NextMatch() methods..

3.Drag a label onto the form design surface, and change its Text property to This finds matches for the pattern ‘[A-Z]\d’..

4.Drag a label onto the form design surface, and change its Text property to Enter a string in the text box below:.

5.Drag a text box onto the form design surface, and make its Text property blank.

6.Drag a button onto the form design surface, and change its Text property to Click to find all matches..

7.Drag a text box onto the design surface. Change its Multiline property to True. Change its Text property so that it is blank.

8.Size and align the form controls so that they resemble those shown in Figure 22-11.

533

Chapter 22

Figure 22-11

9.Add the following code below the other using directives:

using System.Text.RegularExpressions;

10.Double-click the button to create the button1_Click() function, and add the following code:

Regex myRegex = new Regex(@”[A-Z]\d”); string inputString = this.textBox1.Text; Match myMatch = myRegex.Match(inputString);

this.textBox2.Text = “Here are all the matches:” + Environment.NewLine;

while (myMatch.Success)

{

this.textBox2.Text += myMatch.ToString()+ Environment.NewLine; myMatch = myMatch.NextMatch();

11.Save the code, and press F5 to run it.

12.In the upper text box, enter the text A11 B22 C33 D44; click the button; and inspect the results displayed in the lower text box, as shown in Figure 22-12.

534

C# and Regular Expressions

Figure 22-12

How It Works

The following describes how the code inside the button1_Click() function works.

The myRegex variable is declared, and the pattern [A-Z]\d is assigned to it:

Regex myRegex = new Regex(@”[A-Z]\d”);

The variable inputString is declared and is assigned the value entered by the user in the upper text box:

string inputString = this.textBox1.Text;

The myMatch variable is declared and is assigned the match returned by the Match() method applied to the inputString variable:

Match myMatch = myRegex.Match(inputString);

Some explanatory text is assigned to the Text property of the lower (multiline) text box:

this.textBox2.Text = “Here are all the matches:” + Environment.NewLine;

535