使用长文本中的正则表达式删除字符附近的空格

时间:2013-08-21 08:29:13

标签: c# asp.net .net regex

如何删除长文本中某个字符附近的一个或多个空格。我不想删除与匹配字符串相邻的其他空格。我只想删除匹配字符旁边的所有空格而不是输入字符串的所有空格。例如:

[text][space][space]![space][text]                should result in [text]![text]
[text][space][space]![space][space][space][text]  should result in [text]![text]
[text][space]![space][space][text]                should result in [text]![text]
[text][space]![space][text]                       should result in [text]![text]
[text]![space][space][text]                       should result in [text]![text]
[text][space][space]![text]                       should result in [text]![text]
[text][space][space]!                             should result in [text]!
![space][space][text]                             should result in ![text]

我要写的代码是:

for (int i = 0 to length of string)
{
 if (string[i] == character)  //which is the desired character "!"
 {
  int location = i+1;
  //remove all whitespace after the character till a non-whitespace character
  //is found or string ends
  while (string[location] == whitespace)
  {
   string[location].replace(" ", "");
   location++;
  }

  int location = i-1;
  //remove all whitespace before the character till a non-whitespace character
  //is found or string ends
  while (string[location] == whitespace)
  {
   string[location].replace(" ", "");
   location--;
  }
 }
}

使用正则表达式删除字符附近的空格是否有更好的方法?

更新:我不想删除与匹配字符串相邻的其他空格。例如:

some_text[space]some_other_text[space][space]![space]some_text[space]some_other_text 
is
 some_text[space]some_other_text!some_text[space]some_other_text

1 个答案:

答案 0 :(得分:4)

Regex rgx = new Regex(pattern);
string input = "This is   text with   far  too   much   " + 
                 "whitespace.";
string pattern = "\\s*!\\s*";
string replacement = "!";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

取自http://msdn.microsoft.com/de-de/library/vstudio/xwewhkd1.aspx