3

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?

12
  • 3
    Well what do you expect if you post prematurely!? Commented Dec 20, 2012 at 8:05
  • @WillVousden It was added when I hit enter? I was updating it.There was no way for me to show I was updating it. Commented Dec 20, 2012 at 8:05
  • 1
    Do you mean while (fname.Contains("..")) fname = fname.Replace("..", "."); perhaps? Commented Dec 20, 2012 at 8:15
  • 1
    if you've trouble building your regular expression: try this for building it Commented Dec 20, 2012 at 8:17
  • 1
    @SteffenWinkler sometimes there will be small difference in .net regex and JS. I use sharpdev.ru/Regex/Sharp . It's in russian, but you can use google translate Commented Dec 20, 2012 at 8:24

2 Answers 2

7
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, "_");
Sign up to request clarification or add additional context in comments.

1 Comment

You're not using symbolPattern now, but I know it should be behind Replace(fname, symbolPattern,"_"); Thanks :)
0

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,
        @"&|\#|\{|\}|%|~|\?",
        "_"
    ),
    @"^\.",
    ""
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.