如何删除字符串中两个单词之间的额外空格?

时间:2017-12-22 09:46:05

标签: c# .net

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”之间有一个额外的空格。如何删除这些额外的空格?

3 个答案:

答案 0 :(得分:4)

作为替代方案,拆分并重建你的字符串:

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等于:

  

Hello world 707 y 9

答案 1 :(得分:2)

来自@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

答案 2 :(得分:1)

用空白字符串替换不需要的字符可以解决问题:

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