Sideway
output.to from Sideway
Draft for Information Only

Content

Regular Expression Engine
 Regex Class
  Constructorss
  Fields
  Properties
  Methods
  Explicit Interface Implementations
  Remarks
  Examples
  Applies to
  Thread Safety
  See also
 Source/Reference

Regular Expression Engine

The Regex class of System.Text.RegularExpressions namespace is used to access the regular expression engine of .NET framework.

Regex Class

Represents an immutable regular expression.

NamespaceSystem.Text.RegularExpressions AssembliesSystem.Text.RegularExpressions.dll, System.dll, netstandard.dll
[System.Serializable]
public class Regex : System.Runtime.Serialization.ISerializable
InheritanceObject->Regex DerivedAspCodeRegex, AspEncodedExprRegex, AspExprRegex, CommentRegex, DatabindExprRegex, DataBindRegex, DirectiveRegex, EndTagRegex, GTRegex, IncludeRegex, LTRegex, RunatServerRegex, ServerTagsRegex, SimpleDirectiveRegex, TagRegex, TagRegex35, TextRegex AttributesSerializableAttribute ImplementsISerializable

Constructorss

Regex() Initializes a new instance of the Regexclass.
Regex(SerializationInfo, StreamingContext) Initializes a new instance of the Regexclass by using serialized data.
Regex(String) Initializes a new instance of the Regexclass for the specified regular expression.
Regex(String, RegexOptions) Initializes a new instance of the Regexclass for the specified regular expression, with options that modify the pattern.
Regex(String, RegexOptions, TimeSpan) Initializes a new instance of the Regexclass for the specified regular expression, with options that modify the pattern and a value that specifies how long a pattern matching method should attempt a match before it times out.

Fields

capnames Used by a Regexobject generated by the CompileToAssemblymethod.
caps Used by a Regexobject generated by the CompileToAssemblymethod.
capsize Used by a Regexobject generated by the CompileToAssemblymethod.
capslist Used by a Regexobject generated by the CompileToAssemblymethod.
factory Used by a Regexobject generated by the CompileToAssemblymethod.
InfiniteMatchTimeout Specifies that a pattern-matching operation should not time out.
internalMatchTimeout The maximum amount of time that can elapse in a pattern-matching operation before the operation times out.
pattern Used by a Regexobject generated by the CompileToAssemblymethod.
roptions Used by a Regexobject generated by the CompileToAssemblymethod.

Properties

CacheSize Gets or sets the maximum number of entries in the current static cache of compiled regular expressions.
CapNames Gets or sets a dictionary that maps named capturing groups to their index values.
Caps Gets or sets a dictionary that maps numbered capturing groups to their index values.
MatchTimeout Gets the time-out interval of the current instance.
Options Gets the options that were passed into the Regexconstructor.
RightToLeft Gets a value that indicates whether the regular expression searches from right to left.

Methods

CompileToAssembly(RegexCompilationInfo[], AssemblyName) Compiles one or more specified Regexobjects to a named assembly.
CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[]) Compiles one or more specified Regexobjects to a named assembly with the specified attributes.
CompileToAssembly(RegexCompilationInfo[], AssemblyName, CustomAttributeBuilder[], String) Compiles one or more specified Regexobjects and a specified resource file to a named assembly with the specified attributes.
Equals(Object) Determines whether the specified object is equal to the current object. (Inherited from Object)
Escape(String) Escapes a minimal set of characters (\, *, +, ?, |, {, [, (,), ^, $, ., #, and white space) by replacing them with their escape codes. This instructs the regular expression engine to interpret these characters literally rather than as metacharacters.
GetGroupNames() Returns an array of capturing group names for the regular expression.
GetGroupNumbers() Returns an array of capturing group numbers that correspond to group names in an array.
GetHashCode() Serves as the default hash function. (Inherited from Object)
GetType() Gets the Typeof the current instance. (Inherited from Object)
GroupNameFromNumber(Int32) Gets the group name that corresponds to the specified group number.
GroupNumberFromName(String) Returns the group number that corresponds to the specified group name.
InitializeReferences() Used by a Regexobject generated by the CompileToAssemblymethod.
IsMatch(String) Indicates whether the regular expression specified in the Regexconstructor finds a match in a specified input string.
IsMatch(String, Int32) Indicates whether the regular expression specified in the Regexconstructor finds a match in the specified input string, beginning at the specified starting position in the string.
IsMatch(String, String) Indicates whether the specified regular expression finds a match in the specified input string.
IsMatch(String, String, RegexOptions) Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options.
IsMatch(String, String, RegexOptions, TimeSpan) Indicates whether the specified regular expression finds a match in the specified input string, using the specified matching options and time-out interval.
Match(String) Searches the specified input string for the first occurrence of the regular expression specified in the Regexconstructor.
Match(String, Int32) Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position in the string.
Match(String, Int32, Int32) Searches the input string for the first occurrence of a regular expression, beginning at the specified starting position and searching only the specified number of characters.
Match(String, String) Searches the specified input string for the first occurrence of the specified regular expression.
Match(String, String, RegexOptions) Searches the input string for the first occurrence of the specified regular expression, using the specified matching options.
Match(String, String, RegexOptions, TimeSpan) Searches the input string for the first occurrence of the specified regular expression, using the specified matching options and time-out interval.
Matches(String) Searches the specified input string for all occurrences of a regular expression.
Matches(String, Int32) Searches the specified input string for all occurrences of a regular expression, beginning at the specified starting position in the string.
Matches(String, String) Searches the specified input string for all occurrences of a specified regular expression.
Matches(String, String, RegexOptions) Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options.
Matches(String, String, RegexOptions, TimeSpan) Searches the specified input string for all occurrences of a specified regular expression, using the specified matching options and time-out interval.
MemberwiseClone() Creates a shallow copy of the current Object. (Inherited from Object)
Replace(String, MatchEvaluator) In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluatordelegate.
Replace(String, MatchEvaluator, Int32) In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluatordelegate.
Replace(String, MatchEvaluator, Int32, Int32) In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a string returned by a MatchEvaluatordelegate.
Replace(String, String) In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
Replace(String, String, Int32) In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.
Replace(String, String, Int32, Int32) In a specified input substring, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.
Replace(String, String, MatchEvaluator) In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluatordelegate.
Replace(String, String, MatchEvaluator, RegexOptions) In a specified input string, replaces all strings that match a specified regular expression with a string returned by a MatchEvaluatordelegate. Specified options modify the matching operation.
Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan) In a specified input string, replaces all substrings that match a specified regular expression with a string returned by a MatchEvaluatordelegate. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
Replace(String, String, String) In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.
Replace(String, String, String, RegexOptions) In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Specified options modify the matching operation.
Replace(String, String, String, RegexOptions, TimeSpan) In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
Split(String) Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regexconstructor.
Split(String, Int32) Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regexconstructor.
Split(String, Int32, Int32) Splits an input string a specified maximum number of times into an array of substrings, at the positions defined by a regular expression specified in the Regexconstructor. The search for the regular expression pattern starts at a specified character position in the input string.
Split(String, String) Splits an input string into an array of substrings at the positions defined by a regular expression pattern.
Split(String, String, RegexOptions) Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. Specified options modify the matching operation.
Split(String, String, RegexOptions, TimeSpan) Splits an input string into an array of substrings at the positions defined by a specified regular expression pattern. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
ToString() Returns the regular expression pattern that was passed into the Regex constructor.
Unescape(String) Converts any escaped characters in the input string.
UseOptionC() Used by a Regexobject generated by the CompileToAssemblymethod.
UseOptionR() Used by a Regexobject generated by the CompileToAssemblymethod.
ValidateMatchTimeout(TimeSpan) Checks whether a time-out interval is within an acceptable range.

Explicit Interface Implementations

ISerializable.GetObjectData(SerializationInfo, StreamingContext) Populates a SerializationInfoobject with the data necessary to deserialize the current Regexobject.

Remarks

  • The Regex class is functioned as the regular expression engine of .NET framework. The Regex class provides a way to find specific character patterns from a specified text stream. The results of the Regex class can then be used to extract, edit, replace, or delete text substrings, and to add the extracted strings to a collection to generate a report.
  • .NET framework also provide the System.Configuration.RegexStringValidator class to validate a string against a specified regular expression pattern.
  • First,  define a regular exprestsion pattern. Next, optionally instantiate a Regex object. Next, specify the text stream. Finally, some operations can be performed by calling some methods.
  • Unlike string method from System.String class, Regex class is used to search for a specific pattern in a string, while System.String class is used to search for a specific string in a string.
  • There are two ways to provide a regular expression pattern to the regular expression engine. One way is to supply both the regular expression and the text to search to a static Regex method. In other word, a regular expression is used without explicitly creating a Regex object. Another way is to instantiate a Regex object that represents the regular expression. The regular expression pattern is pass to a Regex constructor. A Regex object is immutable, therefore when a Regex object is instantiated with a regular expression, the regular expression of that object cannot be changed.
  • All Regex pattern iddentification methods include both static and instance overloads.
  • The regular expression engine must compile a particular pattern before the pattern can be used. Because Regex objects are immutable, this is a one-time procedure that occurs when a Regex class constructor or a static method is called. To eliminate the need to repeatedly compile a single regular expression, the regular expression engine caches the compiled regular expressions used in static method calls. As a result, regular expression pattern-matching methods offer comparable performance for static and instance methods.
  • In the .NET Framework versions 1.0 and 1.1, all compiled regular expressions, whether they were used in instance or static method calls, were cached. Starting with the .NET Framework 2.0, only regular expressions used in static method calls are cached.
  • However, caching can adversely affect performance in two cases. The first case is when using static method calls with a large number of regular expressions. By default, the regular expression engine caches the 15 most recently used static regular expressions. If an application uses more than 15 static regular expressions, some regular expressions must be recompiled. The recomplilation can be prevented by increasing the  Regex.CacheSize property. The second case is when instantiating new Regex objects with regular expressions that have previously been compiled.
  • Regulation expression pattern-matching operations
    • Validation of a match. You call the IsMatch method to determine whether a match is present.

    • Retrieval of a single match. You call the Match method to retrieve a Match object that represents the first match in a string or in part of a string. Subsequent matches can be retrieved by calling the Match.NextMatch method.

    • Retrieval of all matches. You call the Matches method to retrieve a System.Text.RegularExpressions.MatchCollection object that represents all the matches found in a string or in part of a string.

    • Replacement of matched text. You call the Replace method to replace matched text. The replacement text can also be defined by a regular expression. In addition, some of the Replace methods include a MatchEvaluator parameter that enables you to programmatically define the replacement text.

    • Creation of a string array that is formed from parts of an input string. You call the Split method to split an input string at positions that are defined by the regular expression.

  • Regular Expressions special-purpose methods

    • The Escape method escapes any characters that may be interpreted as regular expression operators in a regular expression or input string.

    • The Unescape method removes these escape characters.

    • The CompileToAssembly method creates an assembly that contains predefined regular expressions. The .NET Framework contains examples of these special-purpose assemblies in the System.Web.RegularExpressions namespace.

  • Defining a Time-Out Value.

    The .NET Framework supports a full-featured regular expression language that provides substantial power and flexibility in pattern matching. However, the power and flexibility come at a cost: the risk of poor performance. Regular expressions that perform poorly are surprisingly easy to create. In some cases, regular expression operations that rely on excessive backtracking can appear to stop responding when they process text that nearly matches the regular expression pattern. For more information about the .NET Framework regular expression engine, see Details of Regular Expression Behavior. For more information about excessive backtracking, see Backtracking.

    Starting with the .NET Framework 4.5, you can define a time-out interval for regular expression matches. If the regular expression engine cannot identify a match within this time interval, the matching operation throws a RegexMatchTimeoutException exception. In most cases, this prevents the regular expression engine from wasting processing power by trying to match text that nearly matches the regular expression pattern. It also could indicate, however, that the timeout interval has been set too low, or that the current machine load has caused an overall degradation in performance.

    How you handle the exception depends on the cause of the exception. If the exception occurs because the time-out interval is set too low or because of excessive machine load, you can increase the time-out interval and retry the matching operation. If the exception occurs because the regular expression relies on excessive backtracking, you can assume that a match does not exist, and, optionally, you can log information that will help you modify the regular expression pattern.

    You can set a time-out interval by calling the Regex(String, RegexOptions, TimeSpan) constructor when you instantiate a regular expression object. For static methods, you can set a time-out interval by calling an overload of a matching method that has a matchTimeout parameter. If you do not set a time-out value explicitly, the default time-out value is determined as follows:

    • By using the application-wide time-out value, if one exists. This can be any time-out value that applies to the application domain in which the Regex object is instantiated or the static method call is made. You can set the application-wide time-out value by calling the AppDomain.SetData method to assign the string representation of a TimeSpan value to the "REGEX_DEFAULT_MATCH_TIMEOUT" property.

    • By using the value InfiniteMat, if no application-wide time-out value has been set.

    Important: We recommend that you set a time-out value in all regular expression pattern-matching operations. For more information, see Best Practices for Regular Expressions.

Examples

Examples of Regex Class
ASP.NET Code Input:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
       <title>Sample Page</title>
       <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
       <script runat="server">
           Sub Page_Load()
               Dim xpattern As String = "\w+"
               Dim xstring As String = "This is the string for testing"
               Dim xRegex As Regex = New Regex(xpattern, RegexOptions.IgnoreCase)
               Dim xmatchstr As String
               xmatchstr = "Given pattern: """ & xpattern & """<br />"
               xmatchstr = xmatchstr & "Given string: """ & xstring & """<br />"
               xmatchstr = xmatchstr & "Result of Instance Regex.Match(string): """
               xmatchstr = xmatchstr & xRegex.Match(xstring).value & """<br />"
               xmatchstr = xmatchstr & "Result of static Regex.Matches(string,pattern): """
               xmatchstr = xmatchstr & Regex.Matches(xstring,xpattern)(0).value & """<br />"
               lbl01.Text = xmatchstr
           End Sub
       </script>
    </head>
    <body>
       <% Response.Write ("<h1>This is a Sample Page of Regex Class</h1>") %>
       <p>
           <%-- Set on Page_Load --%>
           <asp:Label id="lbl01" runat="server" />
       </p>
    </body>
</html>
HTML Web Page Embedded Output:

Applies to

.NET Framework: 4.8, 4.7.2, 4.7.1, 4.7, 4.6.2, 4.6.1, 4.6, 4.5.2, 4.5.1, 4.5, 4.0, 3.5, 3.0, 2.0, 1.1

Thread Safety

The Regexclass is immutable (read-only) and thread safe. Regexobjects can be created on any thread and shared between threads. For more information, see Thread Safety.

See also

  • RegexStringValidator
  • .NET Framework Regular Expressions
  • Regular Expression Language Elements
  • Regular Expressions - Quick Reference (download in Word format)
  • Regular Expressions - Quick Reference (download in PDF format)

Source/Reference

  • https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions?view=netframework-4.8
  • https://docs.microsoft.com/en-us/dotnet/api/system.text.regularexpressions.regex?view=netframework-4.8

©sideway

ID: 190700021 Last Updated: 7/21/2019 Revision: 0 Ref:

close

References

  1. Active Server Pages,  , http://msdn.microsoft.com/en-us/library/aa286483.aspx
  2. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929%28v=vs.90%29.aspx
  3. ASP Best Practices,  , http://technet.microsoft.com/en-us/library/cc939157.aspx
  4. ASP Built-in Objects,  , http://msdn.microsoft.com/en-us/library/ie/ms524716(v=vs.90).aspx
  5. Response Object,  , http://msdn.microsoft.com/en-us/library/ms525405(v=vs.90).aspx
  6. Request Object,  , http://msdn.microsoft.com/en-us/library/ms524948(v=vs.90).aspx
  7. Server Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525541(v=vs.90).aspx
  8. Application Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525360(v=vs.90).aspx
  9. Session Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms524319(8v=vs.90).aspx
  10. ASPError Object,  , http://msdn.microsoft.com/en-us/library/ms524942(v=vs.90).aspx
  11. ObjectContext Object (IIS),  , http://msdn.microsoft.com/en-us/library/ms525667(v=vs.90).aspx
  12. Debugging Global.asa Files,  , http://msdn.microsoft.com/en-us/library/aa291249(v=vs.71).aspx
  13. How to: Debug Global.asa files,  , http://msdn.microsoft.com/en-us/library/ms241868(v=vs.80).aspx
  14. Calling COM Components from ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524620(v=VS.90).aspx
  15. IIS ASP Scripting Reference,  , http://msdn.microsoft.com/en-us/library/ms524664(v=vs.90).aspx
  16. ASP Keywords,  , http://msdn.microsoft.com/en-us/library/ms524672(v=vs.90).aspx
  17. Creating Simple ASP Pages,  , http://msdn.microsoft.com/en-us/library/ms524741(v=vs.90).aspx
  18. Including Files in ASP Applications,  , http://msdn.microsoft.com/en-us/library/ms524876(v=vs.90).aspx
  19. ASP Overview,  , http://msdn.microsoft.com/en-us/library/ms524929(v=vs.90).aspx
  20. FileSystemObject Object,  , http://msdn.microsoft.com/en-us/library/z9ty6h50(v=vs.84).aspx
  21. http://msdn.microsoft.com/en-us/library/windows/desktop/ms675944(v=vs.85).aspx,  , ADO Object Model
  22. ADO Fundamentals,  , http://msdn.microsoft.com/en-us/library/windows/desktop/ms680928(v=vs.85).aspx
close

Latest Updated LinksValid XHTML 1.0 Transitional Valid CSS!Nu Html Checker Firefox53 Chromena IExplorerna
IMAGE

Home 5

Business

Management

HBR 3

Information

Recreation

Hobbies 8

Culture

Chinese 1097

English 339

Reference 79

Computer

Hardware 249

Software

Application 213

Digitization 32

Latex 52

Manim 205

KB 1

Numeric 19

Programming

Web 289

Unicode 504

HTML 66

CSS 65

SVG 46

ASP.NET 270

OS 429

DeskTop 7

Python 72

Knowledge

Mathematics

Formulas 8

Algebra 84

Number Theory 206

Trigonometry 31

Geometry 34

Coordinate Geometry 2

Calculus 67

Complex Analysis 21

Engineering

Tables 8

Mechanical

Mechanics 1

Rigid Bodies

Statics 92

Dynamics 37

Fluid 5

Fluid Kinematics 5

Control

Process Control 1

Acoustics 19

FiniteElement 2

Natural Sciences

Matter 1

Electric 27

Biology 1

Geography 1


Copyright © 2000-2024 Sideway . All rights reserved Disclaimers last modified on 06 September 2019