簡體   English   中英

用特殊字符刪除字符串上多余的空格

[英]Remove extra white spaces on string with special characters

我無法從以下內容中刪除多余的空格:

abc\ae.exe        a 1 b 2%%  ACU > log.txt

我正在使用以下代碼刪除多余的空間(我在SO上找到):

Regex.Replace(cmdLine, @"^\s*$\n", string.Empty, RegexOptions.Multiline).TrimEnd();

上面的代碼刪除了abc \\ ae.exe之間的多余空格,這很好。 但是,它並沒有從2 %%的ACU中刪除多余的空格(中間有兩個空格)。

我對reg表達式不是很熟悉,但我認為它與%符號可能是reg ex關鍵字這一事實有關。

任何指導將不勝感激。

Regex.Replace(cmdLine,@"\s+"," ");

將用單個空格替換多個空格

+表示match the character one or more times

這是C#Regex指南

如果您想選擇特定的空白字符而不是\\s包含的所有空白字符,也可以使用“ 字符組”來完成此操作(相當於[ \\f\\n\\r\\t\\v]

string test = @"abc\ae.exe           a 1 b 2%%  ACU > log.txt";
// Replace one more more space characters with a single space
// Add other whitespace characters inside [ ] (ex: \t)
string no_space2 = Regex.Replace(test,@"[ ]+"," ");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM