[筆記]常用的System.Text.RegularExpressions.Regex

  • 5254
  • 0
  • 2012-11-12

摘要:[筆記]常用的System.Text.RegularExpressions.Regex

我是從ASP就開始寫程式的老人,很多方法都是可以用就用
也沒去探究效能,其實負責的系統也沒什麼效能考量,
真的遇到才會去處理。

前陣子91哥在review其他公司的code,有提到
字串用substring去算不是很聰明,可用regular expression來做
當時我也不好意思說我也是這樣用,之前的程式也不好去翻
只好有用到的新程式盡量用

真的要用regular expression還真的有門檻
抄別人的範例可以用,但是變化一下自己就不會用了
只好把網路上找到的一些常用的記錄下來

(一) 搜尋某字串加上變化再取代

http://karrysu.blogspot.tw/2007/07/regular-expression-replace.html

string s = "123abc456abc789";
string pattern = "(?i)(abc)";
MessageBox.Show(Regex.Replace(s, pattern, "-$1-"));

=> 123-abc-456-abc-789

(二)分割字串加上分隔符號

http://yilinliu.blogspot.tw/2010/07/c-regular-expression.html

原來是因為資料庫的時間字串是6碼,想用substring來切
覺得這樣做不是很聰明,就找了一下做法

string s = "112233";
string pattern = "(?!.{2}$)(.{2})";
MessageBox.Show(Regex.Replace(s,pattern,"$1"+":");

=>11:22:33

<

(三)去除最後一個分隔符號

常常程式會用到把多筆資料串接起來用分格符號呈現

for (int i = 0; i < dt.Rows.Count; i++)
{
   s+= dt.Rows[i][0].ToString() + "|";
}

也可以這樣寫就不會有

for (int i = 0; i < dt.Rows.Count; i++)
{
   if(i==dt.Rows.Count-1)
      s+= dt.Rows[i][0].ToString();
   else
      s+= dt.Rows[i][0].ToString()+"|";
}

但是看起來就不漂亮  

以往去掉最後那個符號的做法

s = s.Substring(0, s.Length - 1);

還沒找到好做法orz

(四) 驗證24小時的數字

http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

([01]?[0-9]|2[0-3]):[0-5][0-9]