如何删除非字母数字字符c#

时间:2015-11-24 14:23:34

标签: c# regex

string n = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string m = "DEFGHIJKLMNOPQRSTUVWXYZABC";


Console.Write("Enter a string : ");
string text = Console.ReadLine();

Console.WriteLine();
Console.WriteLine("Applying Caesar cipher ...");
Console.WriteLine();
text = text.Replace(" ", "");
text = text.ToUpper();
Console.WriteLine("Input Text = " + text);
text = text.ToUpper();
Console.Write("Output Text = ");
text = text.Replace(" ", "");
foreach (char i in text) {
    if (i >= 'A' && i <= 'Z') {
        int pos = n.IndexOf(i);
        Console.Write(m[pos]);

    } else {
        Console.Write(i);
    }
}
Console.WriteLine();
Console.WriteLine("Press any key to return to menu");

我需要帮助我如何删除非字母数字字符,例如我输入hello world!我希望我的输入文本和输出文本删除我的!。我尝试使用正则表达式,但我不知道如何在我的字符串文本中正确使用它。

3 个答案:

答案 0 :(得分:2)

  

我尝试使用正则表达式,但我不知道如何在我的字符串文本中正确使用它。

您可以使用

text = Regex.Replace(text, "[^A-Z]", "");

而不是

text = text.Replace(" ", "");

删除A..Z范围之外的所有字符。如果您需要保留其他字符,请将它们添加到正则表达式中的字符类。例如,如果您还想保留十进制数字,请使用[^A-Z0-9]

答案 1 :(得分:0)

如果您只想允许特定字符:

var allowedChars = new HashSet<char>("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMOPQRSTUVWXYZ0123456789");    
text = String.Concat(text.Where(allowedChars.Contains));

Char.IsWhiteSpaceChar.IsLetterOrDigit

text = String.Concat(text.Where(c => Char.IsWhiteSpace(c) || Char.IsLetterOrDigit(c)));

答案 2 :(得分:0)

只需执行以下操作:

var result = string.Concat(text.Where(char.IsLetterOrDigit));
相关问题