我希望一个角色逃脱IsLetterOrDigit

时间:2015-11-17 10:04:56

标签: c# asp.net

我有以下函数检查字符串并仅保留字母和数字。删除所有其他字符。

但是我只想要一个角色" - "逃避这个功能而不是被删除。例如,我希望Jean-Paul能够保持与#34; - "在这两个名字之间。我怎么能这样做?

String NameTextboxString = NameTextbox.Text;
NameTextboxString = new string((from c in NameTextboxString
                                where char.IsLetterOrDigit(c) 
                                select c).ToArray);
nameLabel.Text = NameTextboxString;

3 个答案:

答案 0 :(得分:10)

您可以尝试:

where char.IsLetterOrDigit(c) || c == '-'

希望用户不会输入--lolol-i-am-an-hackerz--

之类的字符串

为了简化您的代码:

nameLabel.Text = new string(NameTextbox.Text.Where((c => char.IsLetterOrDigit(c) || c == '-')).ToArray());

答案 1 :(得分:3)

一点点扩展方法也可以派上用场:

public static class CharExtensions
{
    public static bool IsLetterDigitOrSpecialChar(this char c, 
              params char[] specialCharacters)
    {
        return char.IsLetterOrDigit(c) || specialCharacters.Any(x => c.Equals(x));
    }
}

然后像这样消费它:

NameTextboxString = new string(
        NameTextboxString.Where(x => x.IsLetterDigitOrSpecialChar(('-'))).ToArray());

答案 2 :(得分:0)

您只需在where子句中添加或条件:

from c in name where char.IsLetterOrDigit(c) || c=='-' select c

见下面的完整小提琴:

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var name = ""Jean-Paul@@~()"";
        var cleaned_name= new string((from c in name where char.IsLetterOrDigit(c) || c=='-' select c).ToArray());
        Console.WriteLine(cleaned_name);
    }
}

输出:

Jean-Paul