Regex.Replace Method (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 MatchEvaluator delegate. Additional parameters specify options that modify the matching operation and a time-out interval if no match is found.
Assembly: System (in System.dll)
'Declaration Public Shared Function Replace ( _ input As String, _ pattern As String, _ evaluator As MatchEvaluator, _ options As RegexOptions, _ matchTimeout As TimeSpan _ ) As String
- Type: System.String
The string to search for a match.
- Type: System.String
The regular expression pattern to match.
- Type: System.Text.RegularExpressions.MatchEvaluator
A custom method that examines each match and returns either the original matched string or a replacement string.
- Type: System.Text.RegularExpressions.RegexOptions
A bitwise combination of enumeration values that provide options for matching.
Return ValueType: System.String
A new string that is identical to the input string, except that the replacement string takes the place of each matched string. If pattern is not matched in the current instance, the method returns the current instance unchanged.
A regular expression parsing error occurred.
input, pattern, or evaluator is Nothing.
options is not a valid bitwise combination of RegexOptions values.
matchTimeout is negative, zero, or greater than approximately 24 days.
A time-out occurred. For more information about time-outs, see the Remarks section.
The Regex.Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true:
If the replacement string cannot readily be specified by a regular expression replacement pattern.
If the replacement string results from some processing performed on the matched string.
If the replacement string results from conditional processing.
The pattern parameter consists of regular expression language elements that symbolically describe the string to match. For more information about regular expressions, see .NET Framework Regular Expressions and Regular Expression Language - Quick Reference.
The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.
Your custom method returns a string that replaces the matched input.
If you specify RightToLeft for the options parameter, the search for matches begins at the end of the input string and moves left; otherwise, the search begins at the start of the input string and moves right.
The matchTimeout parameter specifies how long a pattern matching method should try to find a match before it times out. Setting a time-out interval prevents regular expressions that rely on excessive backtracking from appearing to "stop responding when they process input that contains near matches. For more information, see Best Practices for Regular Expressions in the .NET Framework and Backtracking. If no match is found in that time interval, the method throws a RegexMatchTimeoutException exception. matchTimeout overrides any default time-out value defined for the application domain in which the method executes.
Because the method returns input unchanged if there is no match, you can use the Object.ReferenceEquals method to determine whether the method has made any replacements to the input string.Notes to Callers
We recommend that you set the matchTimeout parameter to an appropriate value, such as two seconds. If you disable time-outs by specifying Regex.InfiniteMatchTimeout, the regular expression engine offers slightly better performance. However, you should disable time-outs only under the following conditions:
When the input processed by a regular expression is derived from a known and trusted source or consists of static text. This excludes text that has been dynamically input by users.
When the regular expression pattern has been thoroughly tested to ensure that it efficiently handles matches, non-matches, and near matches.
When the regular expression pattern contains no language elements that are known to cause excessive backtracking when processing a near match.
The following example uses a regular expression to extract the individual words from a string, and then uses a MatchEvaluator delegate to call a method named WordScramble that scrambles the individual letters in the word. To do this, the WordScramble method creates an array that contains the characters in the match. It also creates a parallel array that it populates with random floating-point numbers. The arrays are sorted by calling the Array.Sort(Of TKey, TValue)(TKey(), TValue(), IComparer(Of TKey)) method, and the sorted array is provided as an argument to a String class constructor. This newly created string is then returned by the WordScramble method. The regular expression pattern \w+ matches one or more word characters; the regular expression engine will continue to add characters to the match until it encounters a non-word character, such as a white-space character. The call to the Replace(String, String, MatchEvaluator, RegexOptions) method includes the RegexOptions.IgnorePatternWhitespace option so that the comment in the regular expression pattern \w+ # Matches all the characters in a word. is ignored by the regular expression engine.
Imports System.Collections Imports System.Text.RegularExpressions Module Example Public Sub Main() Dim words As String = "letter alphabetical missing lack release " + _ "penchant slack acryllic laundry cease" Dim pattern As String = "\w+ # Matches all the characters in a word." Dim evaluator As MatchEvaluator = AddressOf WordScrambler Console.WriteLine("Original words:") Console.WriteLine(words) Try Console.WriteLine("Scrambled words:") Console.WriteLine(Regex.Replace(words, pattern, evaluator, RegexOptions.IgnorePatternWhitespace, TimeSpan.FromSeconds(.25))) Catch e As RegexMatchTimeoutException Console.WriteLine("Word Scramble operation timed out.") Console.WriteLine("Returned words:") End Try End Sub Public Function WordScrambler(match As Match) As String Dim arraySize As Integer = match.Value.Length - 1 ' Define two arrays equal to the number of letters in the match. Dim keys(arraySize) As Double Dim letters(arraySize) As Char ' Instantiate random number generator' Dim rnd As New Random() For ctr As Integer = 0 To match.Value.Length - 1 ' Populate the array of keys with random numbers. keys(ctr) = rnd.NextDouble() ' Assign letter to array of letters. letters(ctr) = match.Value.Chars(ctr) Next Array.Sort(keys, letters, 0, arraySize, Comparer.Default) Return New String(letters) End Function End Module ' The example displays output similar to the following: ' Original words: ' letter alphabetical missing lack release penchant slack acryllic laundry cease ' ' Scrambled words: ' etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae
Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.