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

本文关键字:字符 空白 删除 正则表达式 文本 | 更新日期: 2023-09-27 18:28:22

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

[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--;
  }
 }
}

有没有更好的方法可以使用Regex删除角色附近的空白?

更新:我不想删除匹配字符串附近不存在的其他空白。例如:

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

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

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