簡體   English   中英

如何刪除字符串中兩個單詞之間的額外空格?

[英]How to remove extra spaces between two words in a string?

ViewBag.Title = "Hello (123) world"

我想要的是:

“Hello 123 world”

這是我的代碼:

string input = ViewBag.Title;
System.Text.RegularExpressions.Regex re = new 
System.Text.RegularExpressions.Regex("[;\\\\/:*?\"<>|&'()-]");
ViewBag.MetaTitle = re.Replace(input, " "); //" " only one space here

使用這個,我得到:

Hello  123  world

由於括號,“hello”和“123”與“world”之間有一個額外的空格。 如何刪除這些額外的空格?

作為替代方案,拆分並重建您的字符串:

string input = "Hello world (707)(y)(9) ";
System.Text.RegularExpressions.Regex re = new
System.Text.RegularExpressions.Regex("[;\\\\/:*?\"<>|&'()-]");
//split
var x = re.Split(input);
//rebuild
var newString = string.Join(" ", x.Where(c => !string.IsNullOrWhiteSpace(c))
                                  .Select(c => c.Trim()));

newString等於:

你好世界707 y 9

從@SCoutos中的注釋回答OP想要用空格替換某些字符,但前提是字符周圍沒有間距

將正則表達式修改為:

"\\s?[;\\\\/:*?\"<>|&'()-]+\\s?"

所以對於Hello World (707(y)(9)你得到了

Hello World 707 y 9

示例代碼:

const string TARGET_STRING = "Hello World (707(y)(9)";
var regEx = new Regex("\\s?[;\\\\/:*?\"<>|&'()-]+\\s?");
string result = regEx.Replace(TARGET_STRING, " ");

請參閱: https//dotnetfiddle.net/KpFY6X

用空字符串替換不需要的字符就可以了:

ViewBag.MetaTitle = re.Replace(input, "");

暫無
暫無

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

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