如何从字符串中删除除破折号和空格字符外的所有非字母数字字符?


当前回答

正则表达式为[^\w\s\-]*:

使用\s而不是space()更好,因为文本中可能有制表符。

其他回答

想要速食吗?

public static class StringExtensions 
{
    public static string ToAlphaNumeric(this string self,
                                        params char[] allowedCharacters)
    {
        return new string(Array.FindAll(self.ToCharArray(),
                                        c => char.IsLetterOrDigit(c) ||
                                        allowedCharacters.Contains(c)));
    }
}

这将允许您指定您希望允许的字符。

使用Regex有一个更简单的方法。

private string FixString(string str)
{
    return string.IsNullOrEmpty(str) ? str : Regex.Replace(str, "[\\D]", "");
}

下面是一个使用@ata answer作为灵感的扩展方法。

"hello-world123, 456".MakeAlphaNumeric(new char[]{'-'});// yields "hello-world123456"

或者如果您需要除连字符以外的其他字符…

"hello-world123, 456!?".MakeAlphaNumeric(new char[]{'-','!'});// yields "hello-world123456!"


public static class StringExtensions
{   
    public static string MakeAlphaNumeric(this string input, params char[] exceptions)
    {
        var charArray = input.ToCharArray();
        var alphaNumeric = Array.FindAll<char>(charArray, (c => char.IsLetterOrDigit(c)|| exceptions?.Contains(c) == true));
        return new string(alphaNumeric);
    }
}

你可以试试:

string s1 = Regex.Replace(s, "[^A-Za-z0-9 -]", "");

s是你的弦。

正则表达式为[^\w\s\-]*:

使用\s而不是space()更好,因为文本中可能有制表符。