C#正則表達式合並連續空格為單個空格


第一種方法:

      使用 System.Text.RegularExpressions.Regex.Replace()方法

  string result = String.Empty;

  string str = "Just     Test the  Method";
  result = Regex.Replace(str, "\\s{2,}", " ");//s{2,} 中的s表示空格,數字2表示兩個或以上的空格

      MessageBox.Show(result);//結果是:Just Test the Method

 

 

第二種方法:

 

  string result = String.Empty;

  string str = "Just     Test the  Method";

  Regex replaceSpace = new Regex(@"\s{1,}", RegexOptions.IgnoreCase);

  result = replaceSpace.Replace(str, " ").Trim();

      MessageBox.Show(result);//結果是:Just Test the Method

 

參考:http://www.cnblogs.com/computer-lzy/archive/2011/12/07/2279417.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM