简体   繁体   English

正则表达式替换除斜线之外的所有特殊字符?

[英]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. 我正在尝试制定一些正则表达式,它将消除SharePoint在创建文件夹时不会采取的所有特殊字符。

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);
    }

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. 您不需要Regex.Replace用于前两个替换,因此您可以将它们合并为一个,或者,因为它们被相同的字符替换,所以继续使用Regex.Replace但只使用其中一个。 I also took the liberty of actually making your function do something: 我也冒昧地让你的功能做了一些事情:

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

You can do it without regular expressions, though: (untested) 但是,您可以在没有正则表达式的情况下执行此操作:(未经测试)

private string RemoveAndReplaceSpecialCharacters(string input) {
    const string ALLOWED_CHARACTERS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ._-";
    return new string(input.Replace('/', '-').Replace('\\', '-').RemoveAll((c) => !ALLOWED_CHARACTERS.Contains(c)).ToArray());
}
 private void RemoveAndReplaceSpecialCharacters(string input)
    {
        Regex.Replace(input, @"[\\\/]+", "-");
            Regex.Replace(input, @"[^0-9a-zA-Z\._]+", string.Empty);
    }

this? 这个?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM