2017-06-30 11 views
-2

我有一行多行字符串文本,每行都有一些電話號碼加上一些文本或空間字符(字符不是英文),所以我想逐行檢查文本併爲每一行提取電話號碼,並保存在一個豐富的文本框中,我面臨一個問題,那就是如何從字符數組中除去數字以外的任何元素..任何幫助!從字符數組中除去數字以外的任何元素

using(StringReader reader=new StringReader(richTextBox1.Text)) 
      { 
       string line = string.Empty; 
       do 
       { 
        line = reader.ReadLine(); 
        if (line != null) 
        { 
         // Checking if the line contains things other than letters 
         char[] buffer = line.Replace(" ", string.Empty).ToCharArray(); 
         for (int i = 0; i < buffer.Length; i++) 
         { 
          if (!char.IsNumber(buffer[i])) 
          { 
           // Delete any letters or spacial characters 
          } 
         } 

         Regex rx = new Regex("^[730-9]{9}$"); 
         if (rx.IsMatch(line)) 
         { 
          richTextBox2.Text+=line; 
         } 

        } 
       } while (line != null); 

      }} 
+1

不要使用字符數組。遍歷字符串。字符串和數組都不允許刪除元素,所以建立一個* new *字符串。從一個空的字符串變量開始,併爲其添加您希望保留的每個字符。 –

+0

[This](https://stackoverflow.com/a/3210462/2457029)是你在找什麼 – maccettura

+0

@EdPlunkett你可以舉個例子 –

回答

1

Char.IsDigit應該有所幫助:

string lineWithoutNumbers = line.Where(x => Char.IsDigit(x)); 

在你的情況,這樣的事情:

using(StringReader reader=new StringReader(richTextBox1.Text)) 
     { 
      string line = string.Empty; 
      do 
      { 
       line = reader.ReadLine(); 
       if (line != null) 
       { 
        // Checking if the line contains things other than letters 
        line = new String(line.Where(x => Char.IsDigit(x)).ToArray()); //here, we remove all non-digits from the line variable 

        Regex rx = new Regex("^[730-9]{9}$"); 
        if (rx.IsMatch(line)) 
        { 
         richTextBox2.Text+=line; 
        } 

       } 
      } while (line != null); 

     }} 
+0

我想保留號碼 –

+0

可能需要https://stackoverflow.com/questions/11654190/ienumerablechar-to-string – user6144226

+0

@MohammedShfq所以,你會,它只返回號碼 –

相關問題