Assembly: System.Web.RegularExpressions (in system.web.regularexpressions.dll)
The DirectiveRegex class provides a compiled regular expression to parse an ASP.NET directive (<%@ … %>).
The System.Web.RegularExpressions classes are meant to be used by the .NET Framework to parse ASP.NET pages and are not always practical for general applications. For example, many of these classes match only the beginning of a string.
The predefined regular expression pattern used by the DirectiveRegex class is \G<%\s*@(\s*(?<attrname>\w[\w:]*(?=\W))(\s*(?<equal>=)\s*"(?<attrval>[^"]*)"|\s*(?<equal>=)\s*'(?<attrval>[^']*)'|\s*(?<equal>=)\s*(?<attrval>[^\s%>]*)|(?<equal>)(?<attrval>\s*?)))*\s*?%>. This regular expression returns an entire ASP.NET directive, including its beginning and ending tags and all of its contents. In matching beginning tags, it will ignore any white space between the % and @ characters. However, for a match to occur, the directive must start at the beginning of the input stream. For multiple directives to be found in a call to the AspCodeRegex object's Matches method, they must be immediately contiguous to one another. That is, the %> tag that terminates the previous inline code block must be immediately followed by the <%@ tag that begins the next inline code block, without any intervening white space or line breaks.
You can retrieve all ASP.NET directives regardless of intervening white space or line breaks in either of two ways:
By instantiating a Regex object whose regular expression pattern is <%\s*@(\s*(?<attrname>\w[\w:]*(?=\W))(\s*(?<equal>=)\s*"(?<attrval>[^"]*)"|\s*(?<equal>=)\s*'(?<attrval>[^']*)'|\s*(?<equal>=)\s*(?<attrval>[^\s%>]*)|(?<equal>)(?<attrval>\s*?)))*\s*?%>.
By calling the String.IndexOf method to locate the next occurrence of a directive in a string, and then using this position when calling the DirectiveRegex object's Match method. The following example illustrates how to use this technique with the DirectiveRegex object to extract all the ASP.NET directives in a string.
The following example demonstrates the DirectiveRegex class. The example illustrates that a directive matches the regular expression only if it is at the beginning of a string or if it immediately follows the preceding match.
The example reads a file named directives.txt that contains the following ASP.NET directives:
<%@ Page Language="VB" Explicit="true" %><% @IMPORT Namespace="System.Collections" %> <% @IMPORT Namespace="System.Collections.Specialized" %> <% @IMPORT Namespace="System.Collections.Generic" %> <% @IMPORT Namespace="System.Text.RegularExpressions" %>
Windows 98, Windows Server 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter EditionThe Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.