有一个字符串,要过滤掉里面所有非“字母”“数字”“空格(如果是多个连续空格只保留一个)”的所有字符.是用正则表达式做,还是做个函数一个一个字符判断那多个连续空格只保留一个也不知道怎么做。

解决方案 »

  1.   

    先删空格在
    Regex.Replace(str, @"[a-zA-Z0-9]", "");
      

  2.   

    Regex.Replace(str, @"[a-zA-Z0-9]+", "");
      

  3.   

    空格(如果是多个连续空格只保留一个) 
    Regex.Replace(str, @"[ ]+", " ");
      

  4.   


    string str = "aa   bb  cc d";
    str = Regex.Replace(str, @"\s+", " ");
    Console.WriteLine(str);
      

  5.   

    1. Regex.Replace(str, @"[a-zA-Z0-9]", "");2. Regex.Replace(str, @"\s+", " ");这两个是正确的,但使用了第一个就把空格也被删除了,就不能使用第二个了。我要保留空格的。
      

  6.   

    Regex re = new Regex("[^A-Za-z\\d\\s]*");
    Regex re1 = new Regex("\\s{2,}");
    string stra = this.TextBox3.Text;
    stra = re.Replace(stra, "");
    stra = re1.Replace(stra," ");
    this.TextBox4.Text = stra;测试过了
      

  7.   

    Regex.Replace(str, @"[a-zA-Z0-9]+", "");
    Regex.Replace(str, @"[a-zA-Z0-9]", ""); 
     这2个空格没删除啊static void Main(string[] args)
            {
                string str = "aa   bb  cc d";
                str = Regex.Replace(str, @"[a-zA-Z0-9]", "");
                Console.WriteLine(str.Length);
            }6
    Press any key to continue . . .