在C#中用字符串替换多次出现的Period

时间:2014-05-04 13:22:20

标签: c# regex

我正在编写一个代码,我必须用一次匹配替换字符串中多次出现的Period。

我目前正在使用

string output = System.Text.RegularExpressions.Regex.Replace(input, "\\.+", "\\.");

其中input是一个字符串,如" ABCDEF ... GHIJK ... LMNOP"

我试图将我的输出作为" ABCDEF.GHIJK.LMNOP"而且它不起作用。我试过了

string output = System.Text.RegularExpressions.Regex.Replace(input, "\\.+", "");

检查它是否有效。它不是。

我怎么能实现这个目标? 谢谢你的时间!

3 个答案:

答案 0 :(得分:1)

        string input = "one.two..three...four....five";
        string output = System.Text.RegularExpressions.Regex.Replace(input, "\\.+", ".");

        Console.WriteLine(output);
        Console.Read();

你的问题是你有" \。"作为替换字符串。它应该只是"。"

答案 1 :(得分:1)

试试这个:

resultString = Regex.Replace(subjectString, "[.]{2,}", new MatchEvaluator(ComputeReplacement));

它将两个或更多.替换为一个。

Match the character “.” «[.]{2,}»
   Between 2 and unlimited times, as many times as possible, giving back as needed (greedy) «{2,}»

答案 2 :(得分:0)

不要使用RegEx :),因为每个人都更容易

StringBuilder sb = new StringBuilder();
char lastChar = '';

foreach (char c in input) {
  if (c != '.' || lastChar != '.')
     sb.Append(c);

  lastChar = c;
}

string result = sb.ToString();

您必须原谅我任何语法错误。在过去的几个月里,我一直在使用objective-c工作,并且正在我的iPhone上打字。