PixelMuse
PixelMuse

Reputation: 470

Regex to replace all special characters except slashes?

I'm trying to work out some regex that will eliminate all of the special characters that SharePoint won't take when creating a folder.

These are the characters that are not allowed and I am assuming that the bottom regex below will handle all of these. But I want to replace an \ or / with a dash as well.

~ " # % & * : < > ? / \ { | }

So this is what I have so far, but I'm hoping to combine this all into one function, if possible.

 private void RemoveAndReplaceSpecialCharacters(string input)
    {
        Regex.Replace(input, @"\\", @"-");
        Regex.Replace(input, @"/", @"-");
        Regex.Replace(input, @"[^0-9a-zA-Z\._]", string.Empty);
    }

Upvotes: 1

Views: 8680

Answers (3)

Ry-
Ry-

Reputation: 224859

You don't need Regex.Replace for the first two replacements, so you could combine those into one, or, since they are replaced by the same character, continue using Regex.Replace but only one of those.

private string RemoveAndReplaceSpecialCharacters(string input) {
    return Regex.Replace(Regex.Replace(input, @"[\\/]", "-"),
                         @"[^0-9a-zA-Z._]", string.Empty);
}

Upvotes: 5

Kakashi
Kakashi

Reputation: 2195

this?

var foo = @"aa\b\hehe";
var baa = Regex.Replace(foo, @"[^\\/]+", "-"); 

Upvotes: 0

Royi Namir
Royi Namir

Reputation: 148514

 private void RemoveAndReplaceSpecialCharacters(string input)
    {
        Regex.Replace(input, @"[\\\/]+", "-");
            Regex.Replace(input, @"[^0-9a-zA-Z\._]+", string.Empty);
    }

Upvotes: 0

Related Questions