![]() |
痴情的铁板烧 · Headers - Web API | MDN· 8 月前 · |
![]() |
考研的西红柿 · Kaggle练习赛---Titanic的分析 ...· 1 年前 · |
![]() |
文质彬彬的椰子 · [Spring Boot] JPA ...· 1 年前 · |
![]() |
仗义的电脑桌 · Python函数之形参与实参-腾讯云开发者社 ...· 1 年前 · |
![]() |
含蓄的弓箭 · Window sizes and ...· 1 年前 · |
public:
System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count, int startat);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator * int * int -> string
Public Function Replace (input As String, evaluator As MatchEvaluator, count As Integer, startat As Integer) As String
Regex.Replace(String, MatchEvaluator, Int32, Int32) 如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:
方法等效于调用
Regex.Matches(String, Int32)
方法并将返回
MatchCollection
的集合中的第一个
count
Match
对象传递给
evaluator
委托。
有关 的
startat
更多详细信息,请参阅 的
Match(String, Int32)
“备注”部分。
正则表达式是由当前 Regex 对象的构造函数定义的模式。
参数
evaluator
是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能与委托匹配
MatchEvaluator
。
public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String
自定义方法将返回替换匹配输入的字符串。
RegexMatchTimeoutException
如果替换操作的执行时间超过构造函数指定的
Regex.Regex(String, RegexOptions, TimeSpan)
超时间隔,则会引发异常。 如果在调用构造函数时未设置超时间隔,则当操作超过为创建对象的应用程序域
Regex
建立的任何超时值时,将引发异常。 如果在构造函数调用或应用程序域的属性中
Regex
未定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement);
public static string Replace (string input, string pattern, string replacement);
static member Replace : string * string * string -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String) As String
string input = "This is text with far too much " +
"white space.";
string pattern = "\\s+";
string replacement = " ";
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
// The example displays the following output:
// Original String: This is text with far too much white space.
// Replacement String: This is text with far too much white space.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "This is text with far too much " + _
"white space."
Dim pattern As String = "\s+"
Dim replacement As String = " "
Dim result As String = Regex.Replace(input, pattern, replacement)
Console.WriteLine("Original String: {0}", input)
Console.WriteLine("Replacement String: {0}", result)
End Sub
End Module
' The example displays the following output:
' Original String: This is text with far too much white space.
' Replacement String: This is text with far too much white space.
以下示例使用
Replace(String, String, String)
方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。 正则表达式使用
Environment.MachineName
属性包含本地计算机的名称,并使用
Environment.GetLogicalDrives
方法包含逻辑驱动器的名称。 若要成功运行该示例,应将文本字符串“MyMachine”替换为本地计算机名称。
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
// Get drives available on local computer and form into a single character expression.
string[] drives = Environment.GetLogicalDrives();
string driveNames = String.Empty;
foreach (string drive in drives)
driveNames += drive.Substring(0,1);
// Create regular expression pattern dynamically based on local machine information.
string pattern = @"\\\\(?i:" + Environment.MachineName + @")(?:\.\w+)*\\((?i:[" + driveNames + @"]))\$";
string replacement = "$1:";
string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt",
@"\\MyMachine\c$\ThingsToDo.txt",
@"\\MyMachine\d$\documents\mydocument.docx" };
foreach (string uncPath in uncPaths)
Console.WriteLine("Input string: " + uncPath);
Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement));
Console.WriteLine();
// The example displays the following output if run on a machine whose name is
// MyMachine:
// Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
// Returned string: C:\ThingsToDo.txt
// Input string: \\MyMachine\c$\ThingsToDo.txt
// Returned string: c:\ThingsToDo.txt
// Input string: \\MyMachine\d$\documents\mydocument.docx
// Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
' Get drives available on local computer and form into a single character expression.
Dim drives() As String = Environment.GetLogicalDrives()
Dim driveNames As String = Nothing
For Each drive As String In drives
driveNames += drive.Substring(0,1)
' Create regular expression pattern dynamically based on local machine information.
Dim pattern As String = "\\\\(?i:" + Environment.MachineName + ")(?:\.\w+)*\\((?i:[" + driveNames + "]))\$"
Dim replacement As String = "$1:"
Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
"\\MyMachine\c$\ThingsToDo.txt", _
"\\MyMachine\d$\documents\mydocument.docx" }
For Each uncPath As String In uncPaths
Console.WriteLine("Input string: " + uncPath)
Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement))
Console.WriteLine()
End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
' Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
' Returned string: C:\ThingsToDo.txt
' Input string: \\MyMachine\c$\ThingsToDo.txt
' Returned string: c:\ThingsToDo.txt
' Input string: \\MyMachine\d$\documents\mydocument.docx
' Returned string: d:\documents\mydocument.docx
正则表达式模式由以下表达式定义:
"\\\\(?i:" + Environment.MachineName + ")(?:\.\w+)*\\((?i:[" + driveNames + "]))\$"
下表演示了如何解释正则表达式模式。
静态
Replace
方法等效于使用指定的正则表达式模式构造
Regex
对象并调用实例方法
Replace
。
参数
pattern
由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅
.NET 正则表达式
和
正则表达式语言 - 快速参考
。 搜索匹配项从字符串的
input
开头开始。
参数
replacement
指定要替换 中的每个匹配项的
input
字符串。
replacement
可以包含文本文本和
替换的
任意组合。 例如,替换模式
a*${test}b
插入字符串“a*”,后跟捕获组匹配
test
的子字符串(如果有),后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。
替换是在替换模式中识别的唯一正则表达式语言元素。 所有其他正则表达式语言元素(包括
字符转义
)仅允许在正则表达式模式中使用,在替换模式中不会被识别。
RegexMatchTimeoutException
如果替换操作的执行时间超过为调用方法的应用程序域指定的超时间隔,则会引发异常。 如果未在应用程序域的属性中定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常。
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions * TimeSpan -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator, options As RegexOptions, matchTimeout As TimeSpan) As String
以下示例使用正则表达式从字符串中提取各个单词,然后使用
MatchEvaluator
委托调用名为
WordScramble
的方法,该方法对单词中的单个字母进行拼音。 为此,
WordScramble
方法将创建一个数组,其中包含匹配中的字符。 它还会创建一个用随机浮点数填充的并行数组。 通过调用
Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)
方法对数组进行排序,排序的数组作为类构造函数的参数
String
提供。 然后, 方法将返回
WordScramble
此新创建的字符串。 正则表达式模式
\w+
匹配一个或多个单词字符;正则表达式引擎将继续向匹配项添加字符,直到遇到非单词字符(如空白字符)。 对 方法的
Replace(String, String, MatchEvaluator, RegexOptions)
调用包括
RegexOptions.IgnorePatternWhitespace
选项,以便正则表达式引擎忽略正则表达式模式
\w+ # Matches all the characters in a word.
中的注释。
using System;
using System.Collections;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string words = "letter alphabetical missing lack release " +
"penchant slack acryllic laundry cease";
string pattern = @"\w+ # Matches all the characters in a word.";
MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
Console.WriteLine("Original words:");
Console.WriteLine(words);
Console.WriteLine();
try {
Console.WriteLine("Scrambled words:");
Console.WriteLine(Regex.Replace(words, pattern, evaluator,
RegexOptions.IgnorePatternWhitespace,
TimeSpan.FromSeconds(.25)));
catch (RegexMatchTimeoutException) {
Console.WriteLine("Word Scramble operation timed out.");
Console.WriteLine("Returned words:");
public static string WordScrambler(Match match)
int arraySize = match.Value.Length;
// Define two arrays equal to the number of letters in the match.
double[] keys = new double[arraySize];
char[] letters = new char[arraySize];
// Instantiate random number generator'
Random rnd = new Random();
for (int ctr = 0; ctr < match.Value.Length; ctr++)
// Populate the array of keys with random numbers.
keys[ctr] = rnd.NextDouble();
// Assign letter to array of letters.
letters[ctr] = match.Value[ctr];
Array.Sort(keys, letters, 0, arraySize, Comparer.Default);
return new String(letters);
// 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
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)
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)
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
Regex.Replace(String, String, MatchEvaluator, RegexOptions)
如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:
如果正则表达式替换模式无法轻松指定替换字符串。
如果替换字符串来自对匹配字符串执行的某种处理。
如果替换字符串来自条件处理。
方法等效于调用
Regex.Matches(String, String, RegexOptions)
方法并将返回
MatchCollection
的集合中的每个
Match
对象传递给
evaluator
委托。
参数
pattern
由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅
.NET 正则表达式
和
正则表达式语言 - 快速参考
。
参数
evaluator
是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能与委托匹配
MatchEvaluator
。
public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String
自定义方法将返回替换匹配输入的字符串。
如果为
options
参数指定
RightToLeft
,则搜索匹配项从输入字符串的末尾开始,向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。
参数
matchTimeout
指定模式匹配方法在超时之前应尝试查找匹配项的时间。设置超时间隔可防止依赖于过度回溯的正则表达式出现“在处理包含接近匹配项的输入时停止响应”。 有关详细信息,请参阅
正则表达式的最佳做法
和
回溯
。 如果在该时间间隔内找不到匹配项,该方法将
RegexMatchTimeoutException
引发异常。
matchTimeout
替代为执行方法的应用程序域定义的任何默认超时值。
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
调用方说明
建议将 参数设置为
matchTimeout
适当的值,例如 2 秒。 如果通过指定
InfiniteMatchTimeout
来禁用超时,则正则表达式引擎的性能稍好一些。 但是,应仅在以下情况下禁用超时:
当正则表达式处理的输入派生自已知且受信任的源或由静态文本组成时。 这不包括用户动态输入的文本。
当正则表达式模式经过全面测试以确保它有效地处理匹配项、非匹配项和接近匹配项时。
当正则表达式模式不包含已知在处理接近匹配时导致过度回溯的语言元素时。
public:
static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator, options As RegexOptions) As String
以下示例使用正则表达式从字符串中提取各个单词,然后使用
MatchEvaluator
委托调用名为
WordScramble
的方法,该方法对单词中的单个字母进行拼音。 为此,
WordScramble
方法将创建一个数组,其中包含匹配中的字符。 它还会创建一个用随机浮点数填充的并行数组。 通过调用
Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)
方法对数组进行排序,排序的数组作为类构造函数的参数
String
提供。 然后, 方法将返回
WordScramble
此新创建的字符串。 正则表达式模式
\w+
匹配一个或多个单词字符;正则表达式引擎将继续向匹配项添加字符,直到遇到非单词字符(如空白字符)。 对 方法的
Replace(String, String, MatchEvaluator, RegexOptions)
调用包括
RegexOptions.IgnorePatternWhitespace
选项,以便正则表达式引擎忽略正则表达式模式
\w+ # Matches all the characters in a word.
中的注释。
using System;
using System.Collections;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string words = "letter alphabetical missing lack release " +
"penchant slack acryllic laundry cease";
string pattern = @"\w+ # Matches all the characters in a word.";
MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
Console.WriteLine("Original words:");
Console.WriteLine(words);
Console.WriteLine();
Console.WriteLine("Scrambled words:");
Console.WriteLine(Regex.Replace(words, pattern, evaluator,
RegexOptions.IgnorePatternWhitespace));
public static string WordScrambler(Match match)
int arraySize = match.Value.Length;
// Define two arrays equal to the number of letters in the match.
double[] keys = new double[arraySize];
char[] letters = new char[arraySize];
// Instantiate random number generator'
Random rnd = new Random();
for (int ctr = 0; ctr < match.Value.Length; ctr++)
// Populate the array of keys with random numbers.
keys[ctr] = rnd.NextDouble();
// Assign letter to array of letters.
letters[ctr] = match.Value[ctr];
Array.Sort(keys, letters, 0, arraySize, Comparer.Default);
return new String(letters);
// 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
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)
Console.WriteLine("Scrambled words:")
Console.WriteLine(Regex.Replace(words, pattern, evaluator,
RegexOptions.IgnorePatternWhitespace))
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)
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
如果以下任一条件为 true,则
Regex.Replace(String, String, MatchEvaluator, RegexOptions)
方法可用于替换 中的正则表达式匹配项:
正则表达式替换模式无法轻松指定替换字符串。
替换字符串是在匹配字符串上完成的一些处理后产生的。
替换字符串来自条件处理。
方法等效于调用
Regex.Matches(String, String, RegexOptions)
方法并将返回
MatchCollection
的集合中的每个
Match
对象传递给
evaluator
委托。
参数
pattern
由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅
.NET 正则表达式
和
正则表达式语言 - 快速参考
。
参数
evaluator
是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能与委托匹配
MatchEvaluator
。
public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String
自定义方法将返回替换匹配输入的字符串。
如果为
options
参数指定
RightToLeft
,则搜索匹配项从输入字符串的末尾开始,向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。
RegexMatchTimeoutException
如果替换操作的执行时间超过为调用方法的应用程序域指定的超时间隔,则会引发异常。 如果未在应用程序域的属性中定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常。
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace : string * string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String, options As RegexOptions, matchTimeout As TimeSpan) As String
以下示例使用
Replace(String, String, String, RegexOptions, TimeSpan)
方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。 正则表达式使用
Environment.MachineName
属性包含本地计算机的名称,并使用
Environment.GetLogicalDrives
方法包含逻辑驱动器的名称。 所有正则表达式字符串比较不区分大小写,如果在 0.5 秒内找不到匹配项,则任何单个替换操作都会超时。 若要成功运行该示例,应将文本字符串“MyMachine”替换为本地计算机名称。
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
// Get drives available on local computer and form into a single character expression.
string[] drives = Environment.GetLogicalDrives();
string driveNames = String.Empty;
foreach (string drive in drives)
driveNames += drive.Substring(0,1);
// Create regular expression pattern dynamically based on local machine information.
string pattern = @"\\\\" + Environment.MachineName + @"(?:\.\w+)*\\([" + driveNames + @"])\$";
string replacement = "$1:";
string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt",
@"\\MyMachine\c$\ThingsToDo.txt",
@"\\MyMachine\d$\documents\mydocument.docx" };
foreach (string uncPath in uncPaths)
Console.WriteLine("Input string: " + uncPath);
string localPath = null;
try {
localPath = Regex.Replace(uncPath, pattern, replacement,
RegexOptions.IgnoreCase,
TimeSpan.FromSeconds(0.5));
Console.WriteLine("Returned string: " + localPath);
catch (RegexMatchTimeoutException) {
Console.WriteLine("The replace operation timed out.");
Console.WriteLine("Returned string: " + localPath);
if (uncPath.Equals(localPath))
Console.WriteLine("Equal to original path.");
Console.WriteLine("Original string: " + uncPath);
Console.WriteLine();
// The example displays the following output if run on a machine whose name is
// MyMachine:
// Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
// Returned string: C:\ThingsToDo.txt
// Input string: \\MyMachine\c$\ThingsToDo.txt
// Returned string: c:\ThingsToDo.txt
// Input string: \\MyMachine\d$\documents\mydocument.docx
// Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
' Get drives available on local computer and form into a single character expression.
Dim drives() As String = Environment.GetLogicalDrives()
Dim driveNames As String = Nothing
For Each drive As String In drives
driveNames += drive.Substring(0,1)
' Create regular expression pattern dynamically based on local machine information.
Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"
Dim replacement As String = "$1:"
Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
"\\MyMachine\c$\ThingsToDo.txt", _
"\\MyMachine\d$\documents\mydocument.docx" }
For Each uncPath As String In uncPaths
Console.WriteLine("Input string: " + uncPath)
Dim localPath As String = Nothing
localPath = Regex.Replace(uncPath, pattern, replacement,
RegexOptions.IgnoreCase,
TimeSpan.FromSeconds(0.5))
Console.WriteLine("Returned string: " + localPath)
Catch e As RegexMatchTimeoutException
Console.WriteLine("The replace operation timed out.")
Console.WriteLine("Returned string: " + localPath)
If uncPath.Equals(localPath) Then
Console.WriteLine("Equal to original path.")
Console.WriteLine("Original string: " + uncPath)
End If
End Try
Console.WriteLine()
End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
' Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
' Returned string: C:\ThingsToDo.txt
' Input string: \\MyMachine\c$\ThingsToDo.txt
' Returned string: c:\ThingsToDo.txt
' Input string: \\MyMachine\d$\documents\mydocument.docx
' Returned string: d:\documents\mydocument.docx
正则表达式模式由以下表达式定义:
"\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"
下表演示了如何解释正则表达式模式。
静态
Replace
方法等效于使用指定的正则表达式模式构造
Regex
对象并调用实例方法
Replace
。
参数
pattern
由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅
.NET 正则表达式
和
正则表达式语言 - 快速参考
。 如果为
options
参数指定
RightToLeft
,则搜索匹配项从输入字符串的末尾开始,向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。
参数
replacement
指定要替换 中的每个匹配项的
input
字符串。
replacement
可以包含文本文本和
替换的
任意组合。 例如,替换模式
a*${test}b
插入字符串“a*”,后跟捕获组匹配
test
的子字符串(如果有),后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。
替换是在替换模式中识别的唯一正则表达式语言元素。 所有其他正则表达式语言元素(包括
字符转义
)仅允许在正则表达式模式中使用,在替换模式中不会被识别。
参数
matchTimeout
指定模式匹配方法在超时之前应尝试查找匹配项的时间。设置超时间隔可防止依赖过度回溯的正则表达式在处理包含接近匹配项的输入时出现停止响应。 有关详细信息,请参阅
正则表达式的最佳做法
和
回溯
。 如果在该时间间隔内找不到匹配项,该方法将
RegexMatchTimeoutException
引发异常。
matchTimeout
替代为执行方法的应用程序域定义的任何默认超时值。
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
调用方说明
建议将 参数设置为
matchTimeout
适当的值,例如 2 秒。 如果通过指定
InfiniteMatchTimeout
来禁用超时,则正则表达式引擎的性能稍好一些。 但是,应仅在以下情况下禁用超时:
当正则表达式处理的输入派生自已知且受信任的源或由静态文本组成时。 这不包括用户动态输入的文本。
当正则表达式模式经过全面测试以确保它有效地处理匹配项、非匹配项和接近匹配项时。
当正则表达式模式不包含已知在处理接近匹配时导致过度回溯的语言元素时。
public:
static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options);
static member Replace : string * string * string * System.Text.RegularExpressions.RegexOptions -> string
Public Shared Function Replace (input As String, pattern As String, replacement As String, options As RegexOptions) As String
以下示例使用
Replace(String, String, String, RegexOptions)
方法将 UNC 路径中的本地计算机和驱动器名称替换为本地文件路径。 正则表达式使用
Environment.MachineName
属性包含本地计算机的名称,并使用
Environment.GetLogicalDrives
方法包含逻辑驱动器的名称。 所有正则表达式字符串比较不区分大小写。 若要成功运行该示例,应将文本字符串“MyMachine”替换为本地计算机名称。
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
// Get drives available on local computer and form into a single character expression.
string[] drives = Environment.GetLogicalDrives();
string driveNames = String.Empty;
foreach (string drive in drives)
driveNames += drive.Substring(0,1);
// Create regular expression pattern dynamically based on local machine information.
string pattern = @"\\\\" + Environment.MachineName + @"(?:\.\w+)*\\([" + driveNames + @"])\$";
string replacement = "$1:";
string[] uncPaths = { @"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt",
@"\\MyMachine\c$\ThingsToDo.txt",
@"\\MyMachine\d$\documents\mydocument.docx" };
foreach (string uncPath in uncPaths)
Console.WriteLine("Input string: " + uncPath);
Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase));
Console.WriteLine();
// The example displays the following output if run on a machine whose name is
// MyMachine:
// Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
// Returned string: C:\ThingsToDo.txt
// Input string: \\MyMachine\c$\ThingsToDo.txt
// Returned string: c:\ThingsToDo.txt
// Input string: \\MyMachine\d$\documents\mydocument.docx
// Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
' Get drives available on local computer and form into a single character expression.
Dim drives() As String = Environment.GetLogicalDrives()
Dim driveNames As String = Nothing
For Each drive As String In drives
driveNames += drive.Substring(0,1)
' Create regular expression pattern dynamically based on local machine information.
Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"
Dim replacement As String = "$1:"
Dim uncPaths() AS String = {"\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt", _
"\\MyMachine\c$\ThingsToDo.txt", _
"\\MyMachine\d$\documents\mydocument.docx" }
For Each uncPath As String In uncPaths
Console.WriteLine("Input string: " + uncPath)
Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase))
Console.WriteLine()
End Sub
End Module
' The example displays the following output if run on a machine whose name is
' MyMachine:
' Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
' Returned string: C:\ThingsToDo.txt
' Input string: \\MyMachine\c$\ThingsToDo.txt
' Returned string: c:\ThingsToDo.txt
' Input string: \\MyMachine\d$\documents\mydocument.docx
' Returned string: d:\documents\mydocument.docx
正则表达式模式由以下表达式定义:
"\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"
下表演示了如何解释正则表达式模式。
静态
Replace
方法等效于使用指定的正则表达式模式构造
Regex
对象并调用实例方法
Replace
。
参数
pattern
由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅
.NET 正则表达式
和
正则表达式语言 - 快速参考
。 如果为
options
参数指定
RightToLeft
,则搜索匹配项从输入字符串的末尾开始,向左移动;否则,搜索从输入字符串的开头开始,然后向右移动。
参数
replacement
指定要替换 中的每个匹配项的
input
字符串。
replacement
可以包含文本文本和
替换的
任意组合。 例如,替换模式
a*${test}b
插入字符串“a*”,后跟捕获组匹配
test
的子字符串(如果有),后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。
替换是在替换模式中识别的唯一正则表达式语言元素。 所有其他正则表达式语言元素(包括
字符转义
)仅允许在正则表达式模式中使用,在替换模式中不会被识别。
RegexMatchTimeoutException
如果替换操作的执行时间超过为调用方法的应用程序域指定的超时间隔,则会引发异常。 如果未在应用程序域的属性中定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常。
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator -> string
Public Function Replace (input As String, evaluator As MatchEvaluator) As String
Regex rx = new Regex(@"\w+");
string result = rx.Replace(text, new MatchEvaluator(RegExSample.CapText));
Console.WriteLine($"result=[{result}]");
// The example displays the following output:
// text=[four score and seven years ago]
// result=[Four Score And Seven Years Ago]
Imports System.Text.RegularExpressions
Module RegExSample
Function CapText(ByVal m As Match) As String
' Get the matched string.
Dim x As String = m.ToString()
' If the first char is lower case...
If Char.IsLower(x.Chars(0)) Then
' Capitalize it.
Return Char.ToUpper(x.Chars(0)) & x.Substring(1, x.Length - 1)
End If
Return x
End Function
Sub Main()
Dim text As String = "four score and seven years ago"
Console.WriteLine($"text=[{text}]")
Dim rx As New Regex("\w+")
Dim result As String = rx.Replace(text, AddressOf RegExSample.CapText)
Console.WriteLine($"result=[{result}]")
End Sub
End Module
' The example displays the following output:
' text=[four score and seven years ago]
' result=[Four Score And Seven Years Ago]
Regex.Replace(String, MatchEvaluator)
如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:
正则表达式替换模式无法轻松指定替换字符串。
替换字符串是在匹配字符串上完成的一些处理后产生的。
替换字符串来自条件处理。
方法等效于调用
Regex.Matches(String)
方法并将返回
MatchCollection
的集合中的每个
Match
对象传递给
evaluator
委托。
正则表达式是由当前
Regex
对象的构造函数定义的模式。
参数
evaluator
是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能与委托匹配
MatchEvaluator
。
public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String
自定义方法将返回替换匹配输入的字符串。
RegexMatchTimeoutException
如果替换操作的执行时间超过构造函数指定的
Regex.Regex(String, RegexOptions, TimeSpan)
超时间隔,则会引发异常。 如果在调用构造函数时未设置超时间隔,则当操作超过为创建对象的应用程序域
Regex
建立的任何超时值时,将引发异常。 如果在构造函数调用或应用程序域的属性中
Regex
未定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count);
member this.Replace : string * System.Text.RegularExpressions.MatchEvaluator * int -> string
Public Function Replace (input As String, evaluator As MatchEvaluator, count As Integer) As String
以下示例使用正则表达式故意拼错列表中的一半单词。 它使用正则表达式
\w*(ie|ei)\w*
来匹配包含字符“ie”或“ei”的单词。 它将匹配单词的前半部分传递给
ReverseLetter
方法,该方法又使用
Replace(String, String, String, RegexOptions)
方法反转匹配字符串中的“i”和“e”。 其余单词保持不变。
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string input = "deceive relieve achieve belief fierce receive";
string pattern = @"\w*(ie|ei)\w*";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
Console.WriteLine("Original string: " + input);
string result = rgx.Replace(input, new MatchEvaluator(Example.ReverseLetter),
input.Split(' ').Length / 2);
Console.WriteLine("Returned string: " + result);
static string ReverseLetter(Match match)
return Regex.Replace(match.Value, "([ie])([ie])", "$2$1",
RegexOptions.IgnoreCase);
// The example displays the following output:
// Original string: deceive relieve achieve belief fierce receive
// Returned string: decieve releive acheive belief fierce receive
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "deceive relieve achieve belief fierce receive"
Dim pattern As String = "\w*(ie|ei)\w*"
Dim rgx As New Regex(pattern, RegexOptions.IgnoreCase)
Console.WriteLine("Original string: " + input)
Dim result As String = rgx.Replace(input, AddressOf ReverseLetter,
input.Split(" "c).Length \ 2)
Console.WriteLine("Returned string: " + result)
End Sub
Public Function ReverseLetter(match As Match) As String
Return Regex.Replace(match.Value, "([ie])([ie])", "$2$1",
RegexOptions.IgnoreCase)
End Function
End Module
' The example displays the following output:
' Original string: deceive relieve achieve belief fierce receive
' Returned string: decieve releive acheive belief fierce receive
正则表达式
\w*(ie|ei)\w*
的定义如下表所示。
方法中的
ReverseLetter
正则表达式模式
([ie])([ie])
匹配 diphthong“ie”或“ei”中的第一个“i”或“e”,并将字母分配给第一个捕获组。 它匹配第二个“i”或“e”,并将字母分配给第二个捕获组。 然后,通过调用
Replace(String, String, String)
具有替换模式
$2$1
的 方法来反转这两个字符。
Regex.Replace(String, MatchEvaluator, Int32)
如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:
正则表达式替换模式无法轻松指定替换字符串。
替换字符串是在匹配字符串上完成的一些处理后产生的。
替换字符串来自条件处理。
方法等效于调用
Regex.Matches(String)
方法并将返回
MatchCollection
的集合中的第一个
count
Match
对象传递给
evaluator
委托。
正则表达式是由当前
Regex
对象的构造函数定义的模式。
参数
evaluator
是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能与委托匹配
MatchEvaluator
。
public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String
自定义方法将返回替换匹配输入的字符串。
RegexMatchTimeoutException
如果替换操作的执行时间超过构造函数指定的
Regex.Regex(String, RegexOptions, TimeSpan)
超时间隔,则会引发异常。 如果在调用构造函数时未设置超时间隔,则当操作超过为创建对象的应用程序域
Regex
建立的任何超时值时,将引发异常。 如果在构造函数调用或应用程序域的属性中
Regex
未定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator);
static member Replace : string * string * System.Text.RegularExpressions.MatchEvaluator -> string
Public Shared Function Replace (input As String, pattern As String, evaluator As MatchEvaluator) As String
以下示例使用正则表达式从字符串中提取各个单词,然后使用
MatchEvaluator
委托调用名为
WordScramble
的方法,该方法对单词中的单个字母进行拼音。 为此,
WordScramble
方法将创建一个数组,其中包含匹配中的字符。 它还会创建一个用随机浮点数填充的并行数组。 通过调用
Array.Sort<TKey,TValue>(TKey[], TValue[], IComparer<TKey>)
方法对数组进行排序,排序的数组作为类构造函数的参数
String
提供。 然后, 方法将返回
WordScramble
此新创建的字符串。 正则表达式模式
\w+
匹配一个或多个单词字符;正则表达式引擎将继续向匹配项添加字符,直到遇到非单词字符(如空白字符)。
using System;
using System.Collections;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string words = "letter alphabetical missing lack release " +
"penchant slack acryllic laundry cease";
string pattern = @"\w+";
MatchEvaluator evaluator = new MatchEvaluator(WordScrambler);
Console.WriteLine("Original words:");
Console.WriteLine(words);
Console.WriteLine();
Console.WriteLine("Scrambled words:");
Console.WriteLine(Regex.Replace(words, pattern, evaluator));
public static string WordScrambler(Match match)
int arraySize = match.Value.Length;
// Define two arrays equal to the number of letters in the match.
double[] keys = new double[arraySize];
char[] letters = new char[arraySize];
// Instantiate random number generator'
Random rnd = new Random();
for (int ctr = 0; ctr < match.Value.Length; ctr++)
// Populate the array of keys with random numbers.
keys[ctr] = rnd.NextDouble();
// Assign letter to array of letters.
letters[ctr] = match.Value[ctr];
Array.Sort(keys, letters, 0, arraySize, Comparer.Default);
return new String(letters);
// The example displays output similar to the following:
// Original words:
// letter alphabetical missing lack release penchant slack acryllic laundry cease
// Scrambled words:
// elrtte iaeabatlpchl igmnssi lcka aerslee hnpatnce ksacl lialcryc dylruna ecase
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+"
Dim evaluator As MatchEvaluator = AddressOf WordScrambler
Console.WriteLine("Original words:")
Console.WriteLine(words)
Console.WriteLine("Scrambled words:")
Console.WriteLine(Regex.Replace(words, pattern, evaluator))
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)
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:
' elrtte iaeabatlpchl igmnssi lcka aerslee hnpatnce ksacl lialcryc dylruna ecase
Regex.Replace(String, String, MatchEvaluator)
如果以下任一条件为 true, 方法可用于替换正则表达式匹配项:
正则表达式替换模式无法轻松指定替换字符串。
替换字符串是在匹配字符串上完成的一些处理后产生的。
替换字符串来自条件处理。
方法等效于调用
Regex.Matches(String, String)
方法并将返回
MatchCollection
的集合中的每个
Match
对象传递给
evaluator
委托。
参数
pattern
由正则表达式语言元素组成,这些元素以符号方式描述要匹配的字符串。 有关正则表达式的详细信息,请参阅
.NET 正则表达式
和
正则表达式语言 - 快速参考
。
参数
evaluator
是定义并检查每个匹配项的自定义方法的委托。 自定义方法必须具有以下签名才能与委托匹配
MatchEvaluator
。
public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String
自定义方法将返回替换匹配输入的字符串。
RegexMatchTimeoutException
如果替换操作的执行时间超过为调用方法的应用程序域指定的超时间隔,则会引发异常。 如果未在应用程序域的属性中定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常。
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
System::String ^ Replace(System::String ^ input, System::String ^ replacement, int count);
public string Replace (string input, string replacement, int count);
member this.Replace : string * string * int -> string
Public Function Replace (input As String, replacement As String, count As Integer) As String
以下示例将重复字符的前五个匹配项替换为一个字符。 正则表达式模式
(\w)\1
匹配单个字符的连续出现,并将第一个匹配项分配给第一个捕获组。 替换模式
$1
将整个匹配项替换为第一个捕获的组。
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string str = "aabccdeefgghiijkklmm";
string pattern = "(\\w)\\1";
string replacement = "$1";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, replacement, 5);
Console.WriteLine("Original String: '{0}'", str);
Console.WriteLine("Replacement String: '{0}'", result);
// The example displays the following output:
// Original String: 'aabccdeefgghiijkklmm'
// Replacement String: 'abcdefghijkklmm'
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim str As String = "aabccdeefgghiijkklmm"
Dim pattern As String = "(\w)\1"
Dim replacement As String = "$1"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(str, replacement, 5)
Console.WriteLine("Original String: '{0}'", str)
Console.WriteLine("Replacement String: '{0}'", result)
End Sub
End Module
' The example displays the following output:
' Original String: 'aabccdeefgghiijkklmm'
' Replacement String: 'abcdefghijkklmm'
搜索匹配项从字符串的
input
开头开始。 正则表达式是由当前
Regex
对象的构造函数定义的模式。 如果
count
为负数,则替换继续到字符串末尾。 如果
count
超过匹配项数,则替换所有匹配项。
参数
replacement
指定要替换 中的第一个
count
匹配项的
input
字符串。
replacement
可以包含文本文本和
替换的
任意组合。 例如,替换模式
a*${test}b
插入字符串“a*”,后跟捕获组匹配
test
的子字符串(如果有),后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。
替换是在替换模式中识别的唯一正则表达式语言元素。 所有其他正则表达式语言元素(包括
字符转义
)仅允许在正则表达式模式中使用,在替换模式中不会被识别。
RegexMatchTimeoutException
如果替换操作的执行时间超过构造函数指定的
Regex.Regex(String, RegexOptions, TimeSpan)
超时间隔,则会引发异常。 如果在调用构造函数时未设置超时间隔,则当操作超过为创建对象的应用程序域
Regex
建立的任何超时值时,将引发异常。 如果在构造函数调用或应用程序域的属性中
Regex
未定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
System::String ^ Replace(System::String ^ input, System::String ^ replacement);
public string Replace (string input, string replacement);
member this.Replace : string * string -> string
Public Function Replace (input As String, replacement As String) As String
string input = "This is text with far too much " +
"white space.";
string pattern = "\\s+";
string replacement = " ";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
// The example displays the following output:
// Original String: This is text with far too much white space.
// Replacement String: This is text with far too much white space.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "This is text with far too much " + _
"white space."
Dim pattern As String = "\s+"
Dim replacement As String = " "
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)
Console.WriteLine("Original String: {0}", input)
Console.WriteLine("Replacement String: {0}", result)
End Sub
End Module
' The example displays the following output:
' Original String: This is text with far too much white space.
' Replacement String: This is text with far too much white space.
以下示例定义正则表达式
(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?
和替换模式
$2
,从数值中删除前导或尾随货币符号。
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string pattern = @"(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?";
string input = "$17.43 €2 16.33 £0.98 0.43 £43 12€ 17";
string replacement = "$2";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: '{0}'", input);
Console.WriteLine("Replacement String: '{0}'", result);
// The example displays the following output:
// Original String: '$17.43 €2 16.33 £0.98 0.43 £43 12€ 17'
// Replacement String: '17.43 2 16.33 0.98 0.43 43 12 17'
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim pattern As String = "(\p{Sc}\s?)?(\d+\.?((?<=\.)\d+)?)(?(1)|\s?\p{Sc})?"
Dim input As String = "$17.43 €2 16.33 £0.98 0.43 £43 12€ 17"
Dim replacement As String = "$2"
Dim rgx As New Regex(pattern)
Dim result As String = rgx.Replace(input, replacement)
Console.WriteLine("Original String: '{0}'", input)
Console.WriteLine("Replacement String: '{0}'", result)
End Sub
End Module
' The example displays the following output:
' Original String: '$17.43 €2 16.33 £0.98 0.43 £43 12€ 17'
' Replacement String: '17.43 2 16.33 0.98 0.43 43 12 17'
正则表达式模式可以解释为下表中所示内容。
(\d+\.?((?<=\.)\d+)?)
匹配一个或多个十进制数字后跟可选句点和其他十进制数字的模式。 这是第二个捕获组。
Replace(String, String)
调用 方法会将整个匹配项替换为此捕获组的值。
(?(1)|\s?\p{Sc})?
如果存在第一个捕获的组,则匹配空字符串。 否则,匹配零个或一个后跟货币符号的空白字符。
搜索匹配项从字符串的
input
开头开始。 正则表达式是由当前
Regex
对象的构造函数定义的模式。
参数
replacement
指定要替换 中的每个匹配项的
input
字符串。
replacement
可以包含文本文本和
替换的
任意组合。 例如,替换模式
a*${test}b
插入字符串“a*”,后跟捕获组匹配
test
的子字符串(如果有),后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。
替换是在替换模式中识别的唯一正则表达式语言元素。 所有其他正则表达式语言元素(包括
字符转义
)仅允许在正则表达式模式中使用,在替换模式中不会被识别。
RegexMatchTimeoutException
如果替换操作的执行时间超过构造函数指定的
Regex.Regex(String, RegexOptions, TimeSpan)
超时间隔,则会引发异常。 如果在调用构造函数时未设置超时间隔,则当操作超过为创建对象的应用程序域
Regex
建立的任何超时值时,将引发异常。 如果在构造函数调用或应用程序域的属性中
Regex
未定义超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常
由于方法在没有任何匹配项时返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。
public:
System::String ^ Replace(System::String ^ input, System::String ^ replacement, int count, int startat);
public string Replace (string input, string replacement, int count, int startat);
member this.Replace : string * string * int * int -> string
Public Function Replace (input As String, replacement As String, count As Integer, startat As Integer) As String
以下示例将除字符串第一行之外的所有行都用双倍空格。 它定义与文本行匹配的正则表达式模式
^.*$
,调用
Match(String)
方法以匹配字符串的第一行,并使用
Match.Index
和
Match.Count
属性确定第二行的起始位置。
using System;
using System.Text.RegularExpressions;
public class Example
public static void Main()
string input = "Instantiating a New Type\n" +
"Generally, there are two ways that an\n" +
"instance of a class or structure can\n" +
"be instantiated. ";
string pattern = "^.*$";
string replacement = "\n$&";
Regex rgx = new Regex(pattern, RegexOptions.Multiline);
string result = String.Empty;
Match match = rgx.Match(input);
// Double space all but the first line.
if (match.Success)
result = rgx.Replace(input, replacement, -1, match.Index + match.Length + 1);
Console.WriteLine(result);
// The example displays the following output:
// Instantiating a New Type
// Generally, there are two ways that an
// instance of a class or structure can
// be instntiated.
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim input As String = "Instantiating a New Type" + vbCrLf + _
"Generally, there are two ways that an" + vbCrLf + _
"instance of a class or structure can" + vbCrLf + _
"be instantiated. "
Dim pattern As String = "^.*$"
Dim replacement As String = vbCrLf + "$&"
Dim rgx As New Regex(pattern, RegexOptions.Multiline)
Dim result As String = String.Empty
Dim match As Match = rgx.Match(input)
' Double space all but the first line.
If match.Success Then
result = rgx.Replace(input, replacement, -1, match.Index + match.Length + 1)
End If
Console.WriteLine(result)
End Sub
End Module
' The example displays the following output:
' Instantiating a New Type
' Generally, there are two ways that an
' instance of a class or structure can
' be instntiated.
正则表达式模式
^.*$
的定义如下表所示。
替换字符串 (
vbCrLf + "$&"
Visual Basic
"\n$&"
中的 C# ) 在匹配字符串之前添加一个新行。 请注意,
\n
在 C# 示例中,C# 编译器将解释为换行符;它不表示正则表达式字符转义。
搜索匹配项从字符串中的
input
参数指定
startat
位置开始。 正则表达式是构造函数为当前
Regex
对象定义的模式。 如果
count
为负值,则替换将继续到字符串的末尾。 如果
count
超出匹配项数,则替换所有匹配项。
有关 的
startat
更多详细信息,请参阅 的
Match(String, Int32)
“备注”部分。
参数
replacement
指定替换 中每个匹配项的
input
字符串。
replacement
可以包含文本和
替换
的任意组合。 例如,替换模式
a*${test}b
插入字符串“a*”,后跟捕获组匹配
test
的子字符串(如果有),后跟字符串“b”。 * 字符在替换模式中无法识别为元字符。
替换是在替换模式中识别的唯一正则表达式语言元素。 所有其他正则表达式语言元素(包括
字符转义
)仅允许在正则表达式模式中使用,在替换模式中不会被识别。
RegexMatchTimeoutException
如果替换操作的执行时间超过构造函数指定的
Regex.Regex(String, RegexOptions, TimeSpan)
超时间隔,则会引发异常。 如果在调用构造函数时未设置超时间隔,当操作超过为创建对象的应用程序域
Regex
建立的任何超时值时,将引发异常。 如果在构造函数调用或应用程序域的属性中未定义
Regex
超时,或者超时值为
Regex.InfiniteMatchTimeout
,则不会引发异常
由于方法在没有任何匹配项的情况下返回
input
不变,因此可以使用
Object.ReferenceEquals
方法确定是否对输入字符串进行了任何替换。