Rob
Rob

Reputation: 3574

Regex instead of string.replace function

I've seen this CheatSheet for Regex in C#

However, I'm trying to create a regex function which can replace this for me:

while (fname.Contains(".."))
{
    fname = fname.Replace("..", ".");
}
if (fname.StartsWith(".")) { 
    fname=  fname.Remove(0, 1);
}
fname = fname.Replace("&", "_");
fname = fname.Replace("#", "_");
fname = fname.Replace("{", "_");
fname = fname.Replace("}", "_");
fname = fname.Replace("%", "_");
fname = fname.Replace("~", "_");
fname = fname.Replace("?", "_");

I simply don't get how to write the regex which will fix this issue for me. Can anyone give me a hand?

Upvotes: 3

Views: 397

Answers (2)

Dmitrii Dovgopolyi
Dmitrii Dovgopolyi

Reputation: 6301

string dotsPattern = @"\.\.+"; //2 or more dots.
fname=Regex.Replace(fname, dotsPattern ,".");
String firstSymbolDot = @"^\.";
fname = Regex.Replace(fname, firstSymbolDot, String.Empty);
string symbolPattern = "[&#{}%~?]"; //any of given symbol;
string result = Regex.Replace(fname, symbolPattern, "_");

Upvotes: 7

Why are you looping over fname=fname.Replace("..", ".");, are you trying to replace all sequences of more than one dot with just one dot?

That's:

fname=Regex.Replace(fname,@"\.+",".");

As for the others:

fname=Regex.Replace(
    Regex.Replace(
        fname,
        @"&|\#|\{|\}|%|~|\?",
        "_"
    ),
    @"^\.",
    ""
);

Upvotes: 0

Related Questions