C# Replace替換的具體使用
前言
Replace 的作用就是,通過指定內(nèi)容的替換,返回一個(gè)新字符串。
返回值中,已將當(dāng)前字符串中的指定 Unicode 字符或 String 的 所有匹配項(xiàng),替換為指定的新的 Unicode 字符或 String。
一、String.Replace() 的幾個(gè)重載
String.Replace() 總共有四個(gè)重載,分別是:(詳見官網(wǎng):String.Replace 方法)
- Replace(Char, Char)、
- Replace(String, String)、
- Replace(String, String, StringComparison)、
- Replace(String, String, Boolean, CultureInfo)。
下面來逐個(gè)簡單介紹下。
1、Replace(Char, Char)
// 作用: // 將實(shí)例中出現(xiàn)的所有指定 Unicode 字符都替換為另一個(gè)指定的 Unicode 字符。 // 語法: public string Replace (char oldChar, char newChar);
代碼示例:
String str = "1 2 3 4 5 6 7 8 9";
Console.WriteLine($"Original string: {str}");
Console.WriteLine($"CSV string: {str.Replace(' ', ',')}");
// 輸出結(jié)果:
// Original string: "1 2 3 4 5 6 7 8 9"
// CSV string: "1,2,3,4,5,6,7,8,9"現(xiàn)在補(bǔ)充一下關(guān)于 Char 類型:
char 類型關(guān)鍵字是 .NET System.Char 結(jié)構(gòu)類型的別名,它表示 Unicode UTF-16 字符。
| 類型 | 范圍 | 大小 | .NET 類型 | 默認(rèn)值 |
| char | U+0000 到 U+FFFF | 16 位 | System.Char | \0 即 U+0000 |
// 給 Char 類型的變量賦值可以通過多重方式,如下:
var chars = new[]
{
'j', //字符文本
'\u006A', //Unicode 轉(zhuǎn)義序列,它是 \u 后跟字符代碼的十六進(jìn)制表示形式(四個(gè)符號)
'\x006A', //十六進(jìn)制轉(zhuǎn)義序列,它是 \x 后跟字符代碼的十六進(jìn)制表示形式
(char)106, //將字符代碼的值轉(zhuǎn)換為相應(yīng)的 char 值
};
Console.WriteLine(string.Join(" ", chars));
// 輸出的值相同: j j j jchar 類型可隱式轉(zhuǎn)換為以下整型類型:ushort、int、uint、long 和 ulong。
也可以隱式轉(zhuǎn)換為內(nèi)置浮點(diǎn)數(shù)值類型:float、double 和 decimal。
可以顯式轉(zhuǎn)換為 sbyte、byte 和 short 整型類型。
2、String.Replace(String, String)
// 作用: // 實(shí)例中出現(xiàn)的所有指定字符串都替換為另一個(gè)指定的字符串 // 語法: public string Replace (char oldString, char newString);
示例:
// 目的:將錯(cuò)誤的單詞更正
string errString = "This docment uses 3 other docments to docment the docmentation";
Console.WriteLine($"The original string is:{Environment.NewLine}'{errString}'{Environment.NewLine}");
// 正確的拼寫應(yīng)該為 "document"
string correctString = errString.Replace("docment", "document");
Console.WriteLine($"After correcting the string, the result is:{Environment.NewLine}'{correctString}'");
// 輸出結(jié)果:
// The original string is:
// 'This docment uses 3 other docments to docment the docmentation'
//
// After correcting the string, the result is:
// 'This document uses 3 other documents to document the documentation'
//另一個(gè)示例:
// 可進(jìn)行連續(xù)多次替換操作
String s = "aaa";
Console.WriteLine($"The initial string: '{s}'");
s = s.Replace("a", "b").Replace("b", "c").Replace("c", "d");
Console.WriteLine($"The final string: '{s}'");
// 如果 newString 為 null,則將 oldString 的匹配項(xiàng)全部刪掉
s = s.Replace("dd", null);
Console.WriteLine($"The new string: '{s}'");
// 輸出結(jié)果:
//The initial string: 'aaa'
//The final string: 'ddd'
//The new string: 'd'3、Replace(String, String, StringComparison)
相較于上一個(gè)重載,新增了一個(gè)入?yún)⒚杜e類型 StringComparison(詳見官網(wǎng):StringComparison 枚舉)。作用是:指定供 Compare(String, String) 和 Equals(Object) 方法的特定重載,使用的區(qū)域性、大小寫和排序規(guī)則。
相關(guān)源代碼如下,可以看出,不同的 StringComparison 參數(shù)值對應(yīng)的操作不同,最主要的區(qū)別就是是否添加參數(shù) CultureInfo。
public string Replace(string oldValue, string? newValue, StringComparison comparisonType)
{
switch (comparisonType)
{
case StringComparison.CurrentCulture:
case StringComparison.CurrentCultureIgnoreCase:
return ReplaceCore(oldValue, newValue, CultureInfo.CurrentCulture.CompareInfo,
GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.InvariantCulture:
case StringComparison.InvariantCultureIgnoreCase:
return ReplaceCore(oldValue, newValue, CompareInfo.Invariant,
GetCaseCompareOfComparisonCulture(comparisonType));
case StringComparison.Ordinal:
return Replace(oldValue, newValue);
case StringComparison.OrdinalIgnoreCase:
return ReplaceCore(oldValue, newValue, CompareInfo.Invariant, CompareOptions.OrdinalIgnoreCase);
default:
throw new ArgumentException(SR.NotSupported_StringComparison, "comparisonType");
}
}關(guān)于不同區(qū)域的不同 CultureInfo 實(shí)例,程序運(yùn)行結(jié)果的區(qū)別,見下面的示例:
// 以下示例為三種語言("zh-CN", "th-TH", "tr-TR")不同枚舉值的測試代碼和輸出結(jié)果:
String[] cultureNames = { "zh-CN", "th-TH", "tr-TR" }; // 中國 泰國 土耳其
String[] strings1 = { "a", "i", "case", };
String[] strings2 = { "a-", "\u0130", "Case" };
StringComparison[] comparisons = (StringComparison[])Enum.GetValues(typeof(StringComparison));
foreach (var cultureName in cultureNames)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureName);
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.Name);
for (int ctr = 0; ctr <= strings1.GetUpperBound(0); ctr++)
{
foreach (var comparison in comparisons)
Console.WriteLine(" {0} = {1} ({2}): {3}", strings1[ctr], strings2[ctr], comparison,
String.Equals(strings1[ctr], strings2[ctr], comparison));
Console.WriteLine();
}
Console.WriteLine();
}
// 輸出結(jié)果:
// Current Culture: zh-CN
// a = a- (CurrentCulture): False //-----注意------
// a = a- (CurrentCultureIgnoreCase): False //-----注意------
// a = a- (InvariantCulture): False
// a = a- (InvariantCultureIgnoreCase): False
// a = a- (Ordinal): False
// a = a- (OrdinalIgnoreCase): False
//
// i = ? (CurrentCulture): False
// i = ? (CurrentCultureIgnoreCase): False //-----注意------
// i = ? (InvariantCulture): False
// i = ? (InvariantCultureIgnoreCase): False
// i = ? (Ordinal): False
// i = ? (OrdinalIgnoreCase): False
//
// case = Case (CurrentCulture): False
// case = Case (CurrentCultureIgnoreCase): True
// case = Case (InvariantCulture): False
// case = Case (InvariantCultureIgnoreCase): True
// case = Case (Ordinal): False
// case = Case (OrdinalIgnoreCase): True
//
//
// Current Culture: th-TH
// a = a- (CurrentCulture): True //-----注意------
// a = a- (CurrentCultureIgnoreCase): True //-----注意------
// a = a- (InvariantCulture): False
// a = a- (InvariantCultureIgnoreCase): False
// a = a- (Ordinal): False
// a = a- (OrdinalIgnoreCase): False
//
// i = ? (CurrentCulture): False
// i = ? (CurrentCultureIgnoreCase): False
// i = ? (InvariantCulture): False
// i = ? (InvariantCultureIgnoreCase): False
// i = ? (Ordinal): False
// i = ? (OrdinalIgnoreCase): False
//
// case = Case (CurrentCulture): False
// case = Case (CurrentCultureIgnoreCase): True
// case = Case (InvariantCulture): False
// case = Case (InvariantCultureIgnoreCase): True
// case = Case (Ordinal): False
// case = Case (OrdinalIgnoreCase): True
//
//
// Current Culture: tr-TR
// a = a- (CurrentCulture): False
// a = a- (CurrentCultureIgnoreCase): False
// a = a- (InvariantCulture): False
// a = a- (InvariantCultureIgnoreCase): False
// a = a- (Ordinal): False
// a = a- (OrdinalIgnoreCase): False
//
// i = ? (CurrentCulture): False
// i = ? (CurrentCultureIgnoreCase): True //-----注意------
// i = ? (InvariantCulture): False
// i = ? (InvariantCultureIgnoreCase): False
// i = ? (Ordinal): False
// i = ? (OrdinalIgnoreCase): False
//
// case = Case (CurrentCulture): False
// case = Case (CurrentCultureIgnoreCase): True
// case = Case (InvariantCulture): False
// case = Case (InvariantCultureIgnoreCase): True
// case = Case (Ordinal): False
// case = Case (OrdinalIgnoreCase): True4、Replace(String, String, Boolean, CultureInfo)
此重載主要介紹下后兩個(gè)入?yún)ⅰ?/p>
Boolean:布爾類型入?yún)ⅲJ(rèn) false。true:忽略大小寫;false:區(qū)分大小寫。
CultureInfo:指定代碼的區(qū)域性,允許為 null,但必須站位。為空時(shí)取當(dāng)前區(qū)域(CultureInfo.CurrentCulture.CompareInfo)。
注:關(guān)于 CultureInfo 的詳細(xì)測試示例,詳見上一部分中的折疊代碼。
以下是當(dāng)前重載的部分源碼:
public string Replace(string oldValue, string? newValue, bool ignoreCase, CultureInfo? culture)
{
return ReplaceCore(oldValue, newValue, culture?.CompareInfo, ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None);
}
private string ReplaceCore(string oldValue, string newValue, CompareInfo ci, CompareOptions options)
{
if ((object)oldValue == null)
{
throw new ArgumentNullException("oldValue");
}
if (oldValue.Length == 0)
{
throw new ArgumentException(SR.Argument_StringZeroLength, "oldValue");
}
return ReplaceCore(this, oldValue.AsSpan(), newValue.AsSpan(), ci ?? CultureInfo.CurrentCulture.CompareInfo, options) ?? this;
}
private static string ReplaceCore(ReadOnlySpan<char> searchSpace, ReadOnlySpan<char> oldValue, ReadOnlySpan<char> newValue, CompareInfo compareInfo, CompareOptions options)
{
Span<char> initialBuffer = stackalloc char[256];
ValueStringBuilder valueStringBuilder = new ValueStringBuilder(initialBuffer);
valueStringBuilder.EnsureCapacity(searchSpace.Length);
bool flag = false;
while (true)
{
int matchLength;
int num = compareInfo.IndexOf(searchSpace, oldValue, options, out matchLength);
if (num < 0 || matchLength == 0)
{
break;
}
valueStringBuilder.Append(searchSpace.Slice(0, num));
valueStringBuilder.Append(newValue);
searchSpace = searchSpace.Slice(num + matchLength);
flag = true;
}
if (!flag)
{
valueStringBuilder.Dispose();
return null;
}
valueStringBuilder.Append(searchSpace);
return valueStringBuilder.ToString();
}
二、Regex.Replace() 的幾個(gè)常用重載
1、Replace(String, String)
在指定的輸入字符串(input)內(nèi),使用指定的替換字符串(replacement),替換與某個(gè)正則表達(dá)式模式(需要在實(shí)例化 Regex 對象時(shí),將正則表達(dá)式傳入)匹配的所有的字符串。
// 語法 public string Replace (string input, string replacement);
下面是一個(gè)簡單的示例:
// 目的是將多余的空格去掉
string input = "This is text with far too much white space.";
string pattern = "\\s+"; // \s:匹配任何空白字符;+:匹配一次或多次
string replacement = " ";
Regex rgx = new Regex(pattern); // 實(shí)例化時(shí)傳入正則表達(dá)式
string result = rgx.Replace(input, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
// 輸出結(jié)果:
// Original String: This is text with far too much white space.
// Replacement String: This is text with far too much white space.2、Replace(String, String, String)
在指定的輸入字符串內(nèi)(input),使用指定的替換字符串(replacement)替換與指定正則表達(dá)式(pattern)匹配的所有字符串。
// 語法: public static string Replace (string input, string pattern, string replacement);
// 目的:將多余的空格去掉
string input = "This is text with far too much white space.";
string pattern = "\\s+";
// 注:\s 匹配任何空白字符,包括空格、制表符、換頁符等
// 注:+ 重復(fù)一次或多次
string replacement = " "; // 將連續(xù)出現(xiàn)的多個(gè)空格,替換為一個(gè)
string result = Regex.Replace(input, pattern, replacement);
Console.WriteLine("Original String: {0}", input);
Console.WriteLine("Replacement String: {0}", result);
// 輸出結(jié)果:
//Original String: This is text with far too much white space.
//Replacement String: This is text with far too much white space.3、Replace(String, String, Int32, Int32)
在指定輸入子字符串(input)內(nèi),使用指定替換字符串(replacement)替換與某個(gè)正則表達(dá)式模式匹配的字符串(其數(shù)目為指定的最大數(shù)目)。startat 是匹配開始的位置。
// 語法: public string Replace (string input, string replacement, int count, int startat);
下面是一個(gè)示例:
// 目的:添加雙倍行距
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. ";
Console.WriteLine("原內(nèi)容:");
Console.WriteLine(input);
// .:匹配除‘\n'之外的任何單個(gè)字符;*:匹配零次或多次
string pattern = "^.*$"; // ^.*$ 在這里就是匹配每一行中‘\n'前邊的字符串
string replacement = "\n$&"; // 在匹配項(xiàng)前添加‘\n';$&:代表匹配內(nèi)容
Regex rgx = new Regex(pattern, RegexOptions.Multiline); // Multiline:多行模式,不僅僅在整個(gè)字符串的開頭和結(jié)尾匹配
string result = string.Empty;
Match match = rgx.Match(input); // 判斷能否匹配
if (match.Success)
result = rgx.Replace(input,
replacement,
-1, // >= 0 時(shí),就是匹配具體次數(shù),= -1 時(shí)就是不限制次數(shù)
match.Index + match.Length + 1 // 作用就是跳過第一個(gè)匹配項(xiàng)(第一行不做處理)
// 當(dāng)?shù)谝淮纹ヅ鋾r(shí):Index=0,length=除了‘\n'之外的長度,最后再 +1 就是第一行全部的內(nèi)容
);
Console.WriteLine("結(jié)果內(nèi)容:");
Console.WriteLine(result);
// 輸出結(jié)果:
// 原內(nèi)容:
// Instantiating a New Type
// Generally, there are two ways that an
// instance of a class or structure can
// be instantiated.
// 結(jié)果內(nèi)容:
// Instantiating a New Type
//
// Generally, there are two ways that an
//
// instance of a class or structure can
//
// be instantiated.4、Replace(String, String, MatchEvaluator, RegexOptions, TimeSpan)
在入?yún)⒆址╥nput)中,進(jìn)行正則表達(dá)式(pattern)的匹配,匹配成功的,傳遞給 MatchEvaluator 委托(evaluator)處理完成后,替換原匹配值。
RegexOptions 為匹配操作配置項(xiàng)(關(guān)于 RegexOptions 詳見官網(wǎng):RegexOptions 枚舉),TimeSpan 為超時(shí)時(shí)間間隔。
public static string Replace (string input, string pattern,
System.Text.RegularExpressions.MatchEvaluator evaluator,
System.Text.RegularExpressions.RegexOptions options,
TimeSpan matchTimeout);下面是一個(gè)示例:
// 目的:將輸入的每個(gè)單詞中的字母順序隨機(jī)打亂,再一起輸出
static void Main(string[] args)
{
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); // WordScrambler:回調(diào)函數(shù)
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(2)));
}
catch (RegexMatchTimeoutException)
{
Console.WriteLine("Word Scramble operation timed out.");
Console.WriteLine("Returned words:");
}
}
/// <summary>
/// 回調(diào):對全部匹配項(xiàng)逐一進(jìn)行操作
/// </summary>
/// <param name="match"></param>
/// <returns></returns>
public static string WordScrambler(Match match)
{
int arraySize = match.Value.Length;
double[] keys = new double[arraySize]; // 存放隨機(jī)數(shù)
char[] letters = new char[arraySize]; // 存放字母
Random rnd = new Random();
for (int ctr = 0; ctr < match.Value.Length; ctr++)
{
keys[ctr] = rnd.NextDouble(); // 生成隨機(jī)數(shù),用于重新排序
letters[ctr] = match.Value[ctr]; // 將輸入?yún)卧~數(shù)拆解為字母數(shù)組
}
Array.Sort(keys, letters, 0, arraySize, Comparer.Default); // 重新根據(jù)隨機(jī)數(shù)大小排序
return new String(letters);
}
// 輸出結(jié)果:
// Original words:
// letter alphabetical missing lack release penchant slack acryllic laundry cease
//
// Scrambled words:
// eltetr aeplbtaiaclh ignisms lkac elsaree nchetapn acksl lcyaricl udarnly casee三、關(guān)于 Replace 的實(shí)際需求簡單示例
1、全部替換匹配項(xiàng)
string input = "Instantiating Instantiating Instantiating Instantiating";
Console.WriteLine("----原內(nèi)容----");
Console.WriteLine(input);
string result = input.Replace("tiating","*******");
Console.WriteLine("----結(jié)果內(nèi)容----");
Console.WriteLine(result);
// ----原內(nèi)容----
// Instantiating Instantiating Instantiating Instantiating
// ----結(jié)果內(nèi)容----
// Instan******* Instan******* Instan******* Instan*******2、僅替換第一個(gè)匹配項(xiàng)
string input = "Instantiating Instantiating Instantiating Instantiating";
Console.WriteLine("----原內(nèi)容----");
Console.WriteLine(input);
Regex regex = new Regex("tiating");
string result = regex.Replace(input, "*******",1);
Console.WriteLine("----結(jié)果內(nèi)容----");
Console.WriteLine(result);
// ----原內(nèi)容----
// Instantiating Instantiating Instantiating Instantiating
// ----結(jié)果內(nèi)容----
// Instan******* Instantiating Instantiating Instantiating3、僅替換最后一個(gè)匹配項(xiàng)
string input = "Instantiating Instantiating Instantiating Instantiating";
Console.WriteLine("----原內(nèi)容----");
Console.WriteLine(input);
Match match = Regex.Match(input, "tiating",RegexOptions.RightToLeft);
string first = input.Substring(0, match.Index);
string last = input.Length == first.Length + match.Length ? "" :
input.Substring(first.Length + match.Length,input.Length-(first.Length + match.Length));
string result = $"{first}*******{last}";
Console.WriteLine("----結(jié)果內(nèi)容----");
Console.WriteLine(result);
// 兩次測試結(jié)果:
// ----原內(nèi)容----
// Instantiating Instantiating Instantiating Instantiating 345
// ----結(jié)果內(nèi)容----
// Instantiating Instantiating Instantiating Instan******* 345
// ----原內(nèi)容----
// Instantiating Instantiating Instantiating Instantiating
// ----結(jié)果內(nèi)容----
// Instantiating Instantiating Instantiating Instan*******到此這篇關(guān)于C# Replace替換的具體使用的文章就介紹到這了,更多相關(guān)C# Replace替換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
VS2022+unity3D開發(fā)環(huán)境搭建的實(shí)現(xiàn)步驟
本文主要介紹了VS2022+unity3D開發(fā)環(huán)境搭建的實(shí)現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
C#基礎(chǔ)語法:as 運(yùn)算符使用實(shí)例
這篇文章主要介紹了C#基礎(chǔ)語法:as 運(yùn)算符使用實(shí)例,本文給出了類、字符串、數(shù)字、浮點(diǎn)數(shù)、null等值的運(yùn)算實(shí)例,需要的朋友可以參考下2015-06-06
C#中C/S端實(shí)現(xiàn)WebService服務(wù)
本文主要介紹了C#中C/S端實(shí)現(xiàn)WebService服務(wù),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
C#實(shí)現(xiàn)將選中復(fù)選框的信息返回給用戶的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將選中復(fù)選框的信息返回給用戶的方法,涉及C#針對復(fù)選框操作的相關(guān)技巧,需要的朋友可以參考下2015-06-06
C#獲取文件名和文件路徑的兩種實(shí)現(xiàn)方式
這篇文章主要介紹了C#獲取文件名和文件路徑的兩種實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07

