-2

The developer has coded this but it seems like a not so clean implementation also it does not work if the user enters many colons. I would like to use regex but is it possible for regex to check for two or more colons and replace with just two?

renameString = renameString.Replace(":::::::", "::");
renameString = renameString.Replace("::::::", "::");
renameString = renameString.Replace(":::::", "::");
renameString = renameString.Replace("::::", "::");
renameString = renameString.Replace(":::", "::");

Does anyone have any suggestions on a better way that this can be done?

For reference here's the full code for that method:

if (renameString.StartsWith(":") || renameString.EndsWith(":"))
{
    AcceptText.IsEnabled = false;
    IsValidDeckName = false;
}
else
if (renameString.Contains("::"))
{
    renameString = renameString.Replace(":::::::", "::");
    renameString = renameString.Replace("::::::", "::");
    renameString = renameString.Replace(":::::", "::");
    renameString = renameString.Replace("::::", "::");
    renameString = renameString.Replace(":::", "::");
    IsValidDeckName = true;
    AcceptText.IsEnabled = true;
}
else
{
    IsValidDeckName = true;
    AcceptText.IsEnabled = true;

}

Any suggestions on if this can be improved would be appreciated.

Alan2
  • 23,493
  • 79
  • 256
  • 450
  • What should happen if the string contains a sequence of more than seven colons in a row - should the additional colons remain? e.g. if the original string were "::::::::" should the result be ":::"? – PaulF Aug 14 '20 at 12:35
  • 1
    Any more than two colons should just be converted to two colons. – Alan2 Aug 14 '20 at 12:36

2 Answers2

6

Use Regex Regex.Replace(renameString,"::+","::")

ASpirin
  • 3,601
  • 1
  • 23
  • 32
5

Use regular expressions:

renameString = Regex.Replace(renameString, @":{3,}", "::");

In words: replace all sequences of at least 3 occurrences of the character ':' by "::".

Klaus Gütter
  • 11,151
  • 6
  • 31
  • 36