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


当前回答

使用系统。Linq

string withOutSpecialCharacters = new string(stringWithSpecialCharacters.Where(c =>char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-').ToArray());

其他回答

如果你用JS工作,这里有一个非常简洁的版本

myString = myString.replace(/[^A-Za-z0-9 -]/g, "");

基于这个问题的答案,我创建了一个静态类并添加了这些。我觉得可能对某些人有用。

public static class RegexConvert
{
    public static string ToAlphaNumericOnly(this string input)
    {
        Regex rgx = new Regex("[^a-zA-Z0-9]");
        return rgx.Replace(input, "");
    }

    public static string ToAlphaOnly(this string input)
    {
        Regex rgx = new Regex("[^a-zA-Z]");
        return rgx.Replace(input, "");
    }

    public static string ToNumericOnly(this string input)
    {
        Regex rgx = new Regex("[^0-9]");
        return rgx.Replace(input, "");
    }
}

这些方法可用于:

string example = "asdf1234!@#$";
string alphanumeric = example.ToAlphaNumericOnly();
string alpha = example.ToAlphaOnly();
string numeric = example.ToNumericOnly();

下面是一个使用@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);
    }
}

将[^a-zA-Z0-9 -]替换为空字符串。

Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");

我本可以使用RegEx,它们可以提供优雅的解决方案,但它们会导致性能问题。这里有一个解决方案

char[] arr = str.ToCharArray();

arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c) 
                                  || char.IsWhiteSpace(c) 
                                  || c == '-')));
str = new string(arr);

当使用紧凑框架时(它没有FindAll)

将FindAll替换为1

char[] arr = str.Where(c => (char.IsLetterOrDigit(c) || 
                             char.IsWhiteSpace(c) || 
                             c == '-')).ToArray(); 

str = new string(arr);

1 ShawnFeatherly的评论