本文整理汇总了C#中System.Text.RegularExpressions.Regex.Replace方法的典型用法代码示例。如果您正苦于以下问题:C# Regex.Replace方法的具体用法?C# Regex.Replace怎么用?C# Regex.Replace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Text.RegularExpressions.Regex
的用法示例。
在下文中一共展示了Regex.Replace方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
//引入命名空间
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);
}
}
输出:
Original words: letter alphabetical missing lack release penchant slack acryllic laundry cease Scrambled words: etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae
示例2: Main
//引入命名空间
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
示例3: Main
//引入命名空间
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.");
else
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
示例4: Main
//引入命名空间
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);
}
}
输出:
Original words: letter alphabetical missing lack release penchant slack acryllic laundry cease Scrambled words: etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae
示例5: Main
//引入命名空间
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);
}
}
输出:
Instantiating a New Type Generally, there are two ways that an instance of a class or structure can be instntiated.
示例6: Main
//引入命名空间
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);
}
}
输出:
Original words: letter alphabetical missing lack release penchant slack acryllic laundry cease Scrambled words: elrtte iaeabatlpchl igmnssi lcka aerslee hnpatnce ksacl lialcryc dylruna ecase
示例7: Main
//引入命名空间
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
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);
}
}
输出:
Original String: This is text with far too much white space. Replacement String: This is text with far too much white space.
示例8: Main
//引入命名空间
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
示例9: Main
//引入命名空间
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);
}
}
输出:
Original String: 'aabccdeefgghiijkklmm' Replacement String: 'abcdefghijkklmm'
示例10: CapText
//引入命名空间
using System;
using System.Text.RegularExpressions;
class RegExSample
{
static string CapText(Match m)
{
// Get the matched string.
string x = m.ToString();
// If the first char is lower case...
if (char.IsLower(x[0]))
{
// Capitalize it.
return char.ToUpper(x[0]) + x.Substring(1, x.Length - 1);
}
return x;
}
static void Main()
{
string text = "four score and seven years ago";
Console.WriteLine($"text=[{text}]");
Regex rx = new Regex(@"\w+");
string result = rx.Replace(text, new MatchEvaluator(RegExSample.CapText));
Console.WriteLine($"result=[{result}]");
}
}
输出:
text=[four score and seven years ago] result=[Four Score And Seven Years Ago]
示例11: Main
//引入命名空间
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
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);
}
}
输出:
Original String: This is text with far too much white space. Replacement String: This is text with far too much white space.
示例12: Main
//引入命名空间
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);
}
}
输出:
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'
示例13: Main
//引入命名空间
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);
}
}
输出:
Original string: deceive relieve achieve belief fierce receive Returned string: decieve releive acheive belief fierce receive
示例14: Main
//引入命名空间
using System;
using System.Text;
using System.Text.RegularExpressions;
public class MainClass
{
static void Main( string[] args ) {
// Create regex to search for IP address pattern.
string pattern = @"(?<part1>[01]?\d\d?|2[0-4]\d|25[0-5])\." +
@"(?<part2>[01]?\d\d?|2[0-4]\d|25[0-5])\." +
@"(?<part3>[01]?\d\d?|2[0-4]\d|25[0-5])\." +
@"(?<part4>[01]?\d\d?|2[0-4]\d|25[0-5])";
Regex regex = new Regex( pattern );
Match match = regex.Match( "192.168.123.1" );
string replace = @"${part4}.${part3}.${part2}.${part1}" +
@" (the reverse of $&)";
Console.WriteLine( regex.Replace("192.168.123.1", replace) );
}
}