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

C# and Regular Expressions

How It Works

As in the first example in this chapter, a Regex object is instantiated and assigned to the object variable myRegex with the regular expression pattern [A-Z]\d. Because there is a metacharacter that includes a backslash, the @ character precedes the string argument in the Regex() constructor, so you need not double the backslash:

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

After the user has entered a string, the IsMatch() method is used to determine whether the entered string does or does not contain a match:

if (myRegex.IsMatch(inputString))

When the test string contains a match, the bool value True is returned. In this example, the content of the if statement is, therefore, processed. If no match is found, the bool value False is returned, and the else statement is processed:

else

Console.WriteLine(“No match was found.”);

Because the regular expression pattern is [A-Z]\d, the match from the test string J88 is J8.

The Match() Method

The Match() method has the following overloaded methods:

public Match Match(string, inputString);

and:

public Match Match(string inputString,

int startAt);

and:

public Match Match(string inputString, int startAt,

int length);

The inputString argument is tested to determine whether a match is present for the regular expression pattern contained in the Regex object.

As you saw in the first example in this chapter, the Match() method returns a Match object:

Match myMatch = myRegex.Match(inputString);

The Match() method is used when you want to find out whether or not there is a match in a test string. The Regex object’s Match() method can be used together with the Match object’s NextMatch() method to iterate through all matches in a test string. This usage is further discussed in conjunction with the Match object a little later in this chapter.

The Match() method can also be used as a static method, as discussed later in this chapter.

521

Chapter 22

The Matches() Method

When you want to find all the matches in a test string, the Matches() method is the one to use.

Try It Out

The Matches() Method

1.Open Visual Studio 2003, create a new project from the Windows Application template, and name the new project MatchesDemo. Figure 22-4 shows the screen’s appearance. Depending on how you have set options for Visual Studio 2003, the appearance that you see may differ slightly.

Figure 22-4

2.Drag a Label control from the Toolbox to close to the top of the form, and change its Text prop-

erty to This form tests against the pattern ‘[A-Z]\d’.

3.Drag a Label control from the Toolbox onto the form, and change its Text property to Enter a test string:

4.Drag a TextBox control from the Toolbox to the form’s design surface, and change its Text property to be blank.

522

C# and Regular Expressions

5.Drag a Button control to the form, and change its Text property to Click to Find Matches.

6.Drag a TextBox control to the form, and change its Multline property to True and its Text property to be blank. Figure 22-5 shows the desired appearance after this step. You will likely have to tweak the position and size of the controls to achieve an appearance similar to the one shown.

Figure 22-5

At this stage, the form looks reasonably tidy but has no functionality associated with it. Now the code must be created to specify that you are using the System.Text.RegularExpressions namespace.

7.In the Solution Explorer, right-click Form1.cs and select View Code to open the code editor. Scroll up, if necessary, and you will see several using statements:

using System;

using System.Drawing; using System.Collections;

using System.ComponentModel; using System.Windows.Forms; using System.Data;

8.After the final automatically created using statement, add the following new line of code:

using System.Text.RegularExpressions;

523

Chapter 22

9.Return to the design surface. Double-click the Click to Find Matches button. The code editor will open with the following code automatically created for you:

private void button1_Click(object sender, System.EventArgs e)

{

}

The button1_Click event handler responds to a click on the button. You now need to add code to create some functionality when that button is clicked.

10.In the code editor, add the following code between the opening brace and closing brace of the button1_Click event handler:

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

inputString = this.textBox1.ToString();

MatchCollection myMatchCollection = myRegex.Matches(inputString); this.textBox2.Text = “The matches are:” + Environment.NewLine;

foreach(Match myMatch in myMatchCollection)

{

this.textBox2.Text += myMatch.ToString() +

Environment.NewLine;

}

11.Save the code, and press F5 to run it. If the code does not run, take a look at the error messages that appear in the build errors task list. Note the line number that is mentioned in the first error, and attempt to locate and correct that error. Then press F5 to see whether any subsequent errors have also been remedied by correcting the first error.

If you entered the code correctly, you should see a screen with an appearance similar to that shown in Figure 22-6. The exact appearance will depend on how you positioned the form controls and sized the form.

12.Enter the test string K99 L00 M11 in the upper text box.

13.Click the Click to Find Matches button, and inspect the results displayed in the lower text box, as shown in Figure 22-7. Notice that three matches are displayed in the lower text box.

How It Works

To use classes from the System.Text.RegularExpressions namespace, you must add an appropriate using directive:

using System.Text.RegularExpressions;

The work of the simple application is carried out by the code inside the button1_Click function. First, an object variable, myRegex, is declared as inheriting from the Regex class and is assigned the regular expression pattern [A-Z]\d, using the @ syntax to avoid having to double backslash characters inside the paired double quotes.

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

524

C# and Regular Expressions

Figure 22-6

Figure 22-7

525