Recent site activity

C# - C Sharp‎ > ‎

Regular Expressions

The .NET Framework Class Library includes the System.Text.RegularExpressions namespace, which is devoted to creating, executing, and obtaining results from regular expressions executed against a string. Regular expressions take the form of a pattern that can be matched to zero or  more characters within a string. The simplest of these patterns, such as .* (match anything except newline characters) and [A-Za-z] (match any letter) are easy to learn, but more advanced patternscan be difficult to learn and even more difficult to implement correctly. Learning and  understanding regular expressions can take considerable time and effort, but the work will pay off. Regular expression patterns can take a simple form—such as a single word or character— or a much more complex pattern. The more complex patternscan recognize and match such thingsasthe year portion of a date, all of the <SCRIPT> tagsin an ASP page, or a phrase in a sentence that varies with each use. The .NET regular expression classes provide a very flexible and powerful way to do such things as recognize text, replace text within a string, and split up text into individual sections based on one or more complex delimiters. Despite the complexity of regular expression patterns, the regular expression classes in the FCL are easy to use in your applications. Executing a regular expression consists of the following steps:

  1. Create an instance of a Regex object that contains the regular expression pattern along with any options for executing that pattern.
  2. Retrieve a reference to an instance of a Match object by calling the Match instance method if you want only the first match found. Or, retrieve a reference to an instance of the MatchesCollection object by calling the Matches instance method if you want more than just the first match found. If, however, you want to know only whether the input string was a match and do not need the extra details on the nature of the match, you can use the Regex.IsMatch method.
  3. If you’ve called the Matches method to retrieve a MatchCollection object, iterate over the MatchCollection using a foreach loop. Each iteration will allow access to every Match object that the regular expression produced.

Microsoft’s .NET Framework provides a consistent and powerful set of regular expression classes for all .NET implementations. The following sections list the .NET regular expression syntax, the core .NET classes, and C# examples. Microsoft’s .NET uses a Traditional NFA match engine.  For an explanation of the rules behind this engine, see “Introduction to Regexes and Pattern Matching.”