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

Chapter 22

A while loop tests whether there is a successful match, using the Match object’s Success property:

while (myMatch.Success)

{

Inside the while loop, the value of the match retrieved using the ToString() method is concatenated to the string displayed in the lower text box:

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

The NextMatch() method is used to assign the next match in the test string to the myMatch variable:

myMatch = myMatch.NextMatch();

The while loop test, Match.Success, is tested again for the next match, and if it is successful, the string value of the next match is concatenated to the string displayed in the lower text box. If the test fails, the while loop exits;

}

The GroupCollection and Group Classes

The preceding examples in this chapter have used simple patterns. More typically, parentheses in a pattern create groups. All the groups in a match are contained in a GroupCollection object. Each group in the collection is contained in a Group object.

Try It Out

The GroupCollection and Group Classes

1.Create a new project in Visual Studio 2003 from the console application template, and name the project GroupsDemo.

2.In the code editor, enter the following code in the Main() method. Notice that the regular expression pattern in the first line uses two pairs of parentheses, which will create captured groups.

Regex myRegex = new Regex(@”([A-Z])(\d+)”); Console.WriteLine(“Enter a string on the following line:”); string inputString = Console.ReadLine();

MatchCollection myMatchCollection = myRegex.Matches(inputString); Console.WriteLine();

Console.WriteLine(“There are {0} matches.”, myMatchCollection.Count); Console.WriteLine();

GroupCollection myGroupCollection;

foreach (Match myMatch in myMatchCollection)

{

Console.WriteLine(“At position {0}, the match ‘{1}’ was found”, myMatch.Index, myMatch.ToString());

myGroupCollection = myMatch.Groups;

foreach (Group myGroup in myGroupCollection)

{

536

C# and Regular Expressions

Console.WriteLine(“Group containing ‘{0}’ found at position ‘{1}’.”, myGroup.Value, myGroup.Index);

}

Console.WriteLine();

}

Console.WriteLine();

Console.WriteLine(“Press Return to close this application.”);

Console.ReadLine ();

3.Save the code; press F5 to run it; and in the command window, enter the test string A12 B23 C34.

4.Press the Return key, and inspect the results displayed in the command window, as shown in Figure 22-13.

Figure 22-13

How It Works

Let’s look in more detail at the code added to the Main() method. The variable myRegex is declared and is assigned the pattern [A-Z]\d+, which matches an uppercase alphabetic character followed by one or more numeric digits:

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

After displaying a prompt for the user to enter a test string, the myMatchCollection variable is declared, and the Matches() method is applied to the inputString. The result is assigned to the myMatchCollection variable:

Console.WriteLine(“Enter a string on the following line:”); string inputString = Console.ReadLine();

MatchCollection myMatchCollection = myRegex.Matches(inputString);

537

Chapter 22

After a spacer blank line is written to the command window, the number of matches in the Count property of myMatchCollection is displayed:

Console.WriteLine();

Console.WriteLine(“There are {0} matches.”, myMatchCollection.Count);

After an additional blank spacer line, the myGroupCollection variable is declared as inheriting from the GroupCollection class:

Console.WriteLine();

GroupCollection myGroupCollection;

Then nested foreach loops are used to process each match and each group within each match:

foreach (Match myMatch in myMatchCollection)

{

The Match object’s Index property is used to display the position of a match in the test string, together with the substring that constitutes the match:

Console.WriteLine(“At position {0}, the match ‘{1}’ was found”, myMatch.Index,

myMatch.ToString());

For each match, the Groups property, which contains information about all the groups for that match, is assigned to the myGroupCollection variable:

myGroupCollection = myMatch.Groups;

Then each Group object in the myGroupCollection variable is processed using a nested foreach loop:

foreach (Group myGroup in myGroupCollection)

{

The content of each group is displayed using the Group object’s Value property together with the position at which the group is found, using the Index property of the Group object:

Console.WriteLine(“Group containing ‘{0}’ found at position ‘{1}’.”, myGroup.Value,

myGroup.Index);

}

Each match has a zeroth group containing the value of the whole match. Because the pattern ([A- Z])(\d+) contained two additional groups, created by the paired parentheses, there are two additional groups displayed each time the inner foreach loop is processed. So because the pattern has two visible capturing groups (created by the paired parentheses), there are three groups displayed for each match.

Finally, a further spacing line is output each time round the outer foreach loop:

Console.WriteLine();

}

538

C# and Regular Expressions

The RegexOptions Class

The RegexOptions class, a member of the System.Text.RegularExpressions namespace, specifies which of the available options are or are not set.

The following table summarizes the options available using RegexOptions.

Option

Description

 

 

None

Specifies that no options are set.

IgnoreCase

Specifies that matching is case insensitive.

Multiline

Treats each line as a separate string for matching purposes.

 

Therefore, the meaning of the ^ metacharacter is changed

 

(matches the beginning of each line position), as is the $

 

metacharacter (matches the end of each line position).

ExplicitCapture

Changes the capturing behavior of parentheses.

Compiled

Specifies whether or not the regular expression is compiled

 

to an assembly.

SingleLine

Changes the meaning of the period metacharacter so that it

 

matches every character. Normally, it matches every charac-

 

ter except \n.

IgnorePatternWhitespace

Interprets unescaped whitespace as not part of the pattern.

 

Allows comments inline preceded by #.

RightToLeft

Specifies that pattern matching proceeds from the right to

 

the left.

ECMAScript

Enables (limited) ECMAScript compatibility.

CultureInvariant

Specifies that cultural differences in language are ignored.

 

 

The IgnorePatternWhitespace Option

The IgnorePatternWhitespace option allows inline comments to be created that spell out the meaning of each part of the regular expression pattern.

Normally, when a regular expression pattern is matched, any whitespace in the pattern is significant. For example, a space character in the pattern is interpreted as a character to be matched. By setting the IgnorePatternWhitespace option, all whitespace contained in the pattern is ignored, including space characters and newline characters. This allows a single pattern to be laid out over several lines to aid readability, to allow comments to be added, and to aid in maintenance of the regular expression pattern.

The following description assumes that a using System.Text.RegularExpressions; directive is present earlier in the code.

539

Chapter 22

In C#, if you wanted to match a pattern [A-Z]\d using the myRegex variable, you might declare the variable like this:

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

However, if you use the IgnorePatternWhitespace option, you could write it like this:

Regex myRegex = new Regex(

@”[A-Z]

#

Matches

a

single

upper case alphabetic character

\d

#

Matches

a

single

numeric digit”,

RegexOptions.IgnorePatternWhitespace);

As you can see, you can include a comment, preceded by a # character, on each line and split each logical component of the regular expression onto a separate line so that the way the pattern is made up becomes clearer. This is useful particularly when the regular expression pattern is lengthy or complex.

Try It Out

Using the IgnorePatternWhitespace Option

1.Create a new project in Visual Studio 2003 using the Console Application template, and name the project IgnorePatternWhitespaceDemo.

2.In the code editor, add the following line of code after the default using statement(s):

using System.Text.RegularExpressions;

3.Enter the following code inside the Main() method:

Regex myRegex = new Regex(

@”^ # match the position before the first character \d{3} # Three numeric digits, followed by

-# a literal hyphen

\d{2} # then two numeric digits - # then a literal hyphen \d{4} # then two numeric digits

$ # match the position after the last character”, RegexOptions.IgnorePatternWhitespace); Console.WriteLine(“Enter a string on the following line:”); string inputString = Console.ReadLine();

Match myMatch = myRegex.Match(inputString); if (myMatch.ToString().Length != 0)

{

Console.WriteLine(“The match, ‘“ + myMatch.Value + “‘ was found.”);

}

else

{

Console.WriteLine(“There was no match”);

}

Console.WriteLine(“Press Return to close this application.”); Console.ReadLine();

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

5.At the command line, enter the text 123-12-1234 (a U.S. Social Security number [SSN]); press the Return key; and inspect the displayed message, as shown in Figure 22-14.

540

C# and Regular Expressions

Figure 22-14

6.Press the Return key to close the application, and press F5 in Visual Studio 2003 to run the code again.

7.Enter the text 123-12-1234A at the command line, press the Return key, and inspect the displayed message. There is no match for the string entered.

How It Works

This code seeks to match lines where a U.S. SSN is matched, and the line contains no other characters.

The interesting part of the code is how the regular expression can be written when the

IgnorePatternWhitespace option is selected.

The myRegex variable is declared. Instead of writing:

Regex myRegex = new Regex(@”^\d{3}-\d{2}-\d{4}$”;

when you use the IgnorePatternWhitespace option, the pattern can be written over several lines. The @ character allows you to write the \d component of the pattern without having to double the backslash. Any part of the pattern can be written on its own line, and a comment can be supplied following the # character to document each pattern component:

Regex myRegex = new Regex(

@”^ # match the position before the first character \d{3} # Three numeric digits, followed by

-# a literal hyphen

\d{2} # then two numeric digits - # then a literal hyphen \d{4} # then two numeric digits

$# match the position after the last character”,

Finally, the IgnorePatternWhitespace option is specified:

RegexOptions.IgnorePatternWhitespace);

The pattern ^\d{3}-\d{2}-\d{4}$ matches the position at the beginning of a line followed by three numeric digits, followed by a hyphen, followed by two numeric digits, followed by a hyphen, followed by four numeric digits, followed by the end-of-line position. Strings matching this pattern contain a character sequence that is likely to be a U.S. SSN. There are more specific patterns that attempt to reject character sequences that are not valid but that do match this pattern. Because the purpose of this example is to show how to use the IgnorePatternWhitespace option, that issue is explored no further here.

541