替换c#中特定字符之间的空格

时间:2014-05-07 17:43:40

标签: c# regex

我正在寻找一个正则表达式(或任何其他解决方案),它可以让我替换特定非空白字符之间的所有空白字符。例如:

instance. method
instance .method
"instance" .method
instance. "method"

有可能吗?

编辑:

换句话说 - 如果它在字母和点,点和字母,引号和点或点和引号之间,我想抛出空格。

7 个答案:

答案 0 :(得分:5)

使用lookaheads和lookbehinds:

var regex = new Regex("(?<=[a-zA-Z])\\s+(?=\\.)|(?<=\\.)\\s+(?=[a-zA-Z])|(?<=\")\\s+(?=\\.)|(?<=\\.)\\s+(?=\")");

Console.WriteLine(regex.Replace("instance. method", ""));
Console.WriteLine(regex.Replace("instance .method", ""));
Console.WriteLine(regex.Replace("\"instance\" .method", ""));
Console.WriteLine(regex.Replace("instance. \"method\"", ""));

结果:

instance.method
instance.method
"instance".method
instance."method"

正则表达式有四个部分:

(?<=[a-zA-Z])\s+(?=\.) //Matches [a-zA-Z] before and . after:

(?<=\.)\s+(?=[a-zA-Z]) //Matches . before and [a-zA-Z] after

(?<=")\s+(?=\.) //Matches " before and . after

(?<=\.)\s+(?=") //Matches . before and " after

Regular expression visualization

答案 1 :(得分:4)

  

如果它在字母和点,点和字母,引号和点或点和引号之间,我想抛出空格。

我会用这样的东西:

@"(?i)(?:(?<=\.) (?=[""a-z])|(?<=[""a-z]) (?=\.))"

regex101 demo

或分解:

(?i)           // makes the regex case insensitive.
(?:
  (?<=\.)      // ensure there's a dot before the match
  [ ]          // space (enclose in [] if you use the expanded mode, otherwise, you don't need []
  (?=[a-z""])  // ensure there's a letter or quote after the match
|              // OR
  (?<=[a-z""]) // ensure there's a letter or quote before the match
  [ ]          // space
  (?=\.)       // ensure there's a dot after the match
)

Regular expression visualization

在变量中:

var reg = new Regex(@"(?i)(?:(?<=\.) (?=[""a-z])|(?<=[""a-z]) (?=\.))");

答案 2 :(得分:0)

你在google上寻找/搜索的是“Character LookAhead和LookBehind”...基本上你想要做的是使用RegEx来查找空白字符的所有实例或者用Whitespace分割字符串(我更喜欢这个),然后在每场比赛中展望未来,看看这些位置(前一个和下一个)的字符是否符合您的标准。然后在必要时替换该位置。

不幸的是,我不知道你试图做什么的“单一声明”解决方案。

答案 3 :(得分:0)

您可以使用单词边界解析字符串:

^([\w\".]*)([\s])([\w\".]*)$

$ 1将为您提供第一部分。 $ 2将为您提供空白区域。 3美元将给你最终部分。

答案 4 :(得分:0)

这是你寻求的吗? (regex101 link

[A-Za-z"](\s)\.|\.(\s)[A-Za-z"]

答案 5 :(得分:0)

Regex.Replace(instance, "([\\w\\d\".])\\s([\\w\\d\".])", "$1$2");

答案 6 :(得分:0)

一个替代的简单解决方案是将字符串拆分为点,然后修剪它们。

相关问题