How do I remove all non alphanumeric characters fr

2019-01-01 10:02发布

How do I remove all non alphanumeric characters from a string except dash and space characters?

标签: c# regex
12条回答
君临天下
2楼-- · 2019-01-01 10:16

I use a variation of one of the answers here. I want to replace spaces with "-" so its SEO friendly and also make lower case. Also not reference system.web from my services layer.

private string MakeUrlString(string input)
{
    var array = input.ToCharArray();

    array = Array.FindAll<char>(array, c => char.IsLetterOrDigit(c) || char.IsWhiteSpace(c) || c == '-');

    var newString = new string(array).Replace(" ", "-").ToLower();
    return newString;
}
查看更多
倾城一夜雪
3楼-- · 2019-01-01 10:20

I´ve made a different solution, by eliminating the Control characters, which was my original problem.

It is better than putting in a list all the "special but good" chars

char[] arr = str.Where(c => !char.IsControl(c)).ToArray();    
str = new string(arr);

it´s simpler, so I think it´s better !

查看更多
梦该遗忘
4楼-- · 2019-01-01 10:23

Replace [^a-zA-Z0-9 -] with an empty string.

Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
查看更多
深知你不懂我心
5楼-- · 2019-01-01 10:25

Here's an extension method using @ata answer as inspiration.

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

or if you require additional characters other than hyphen...

"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);
    }
}
查看更多
流年柔荑漫光年
6楼-- · 2019-01-01 10:28

The regex is [^\w\s\-]*:

\s is better to use instead of space (), because there might be a tab in the text.

查看更多
怪性笑人.
7楼-- · 2019-01-01 10:29

There is a much easier way with Regex.

private string FixString(string str)
{
    return string.IsNullOrEmpty(str) ? str : Regex.Replace(str, "[\\D]", "");
}
查看更多
登录 后发表回答