[C#] Regular Expression自學筆記| Mike's開發瘋 - - 點部落

文章推薦指數: 80 %
投票人數:10人

&p_cate=all)"; Match match = Regex.Match(categoryUrl, pattern); if (match.Success) { Group g=match.Groups[0]; categoryID = g.ToString(); }. 實戰使用c#Regex的筆記 說明:https://goo.gl/RsQHtp 線上驗證 https://regex101.com/   常用語法說明 特殊字元 \ :後面為特殊符號,e.g \\代表\ , \n代表換行,\(代表( ^ :字串開始 $:字串結尾 .:任何字元除了\n 開頭與結尾 (?=Pattern):前面為pattern   ,e.g Patternabc (?<=Pattern):後面為pattern  ,e.g  abcPattern 集合及字元 [abc]:字元集合,e.g[a-zA-Z] :英文大小寫 [^a-z]:非a-z,e.g ABCdefGH ==> [^a-z] ==>ABC與 GH \d :數字,e.g ABC123DEF==>[\d]* ==>123 \D:非數字,e.g ABC123DEF==>[\D]*==>ABC與DEF \s:一個空白字元 \S:非空白字元 \w:單詞字元(a-z,A-Z,0-9,_) ,e.gNewYork -->\w+==> New與York \W:非單詞字元 出現次數 *:0~n次  +:1~n次 ?: 0-1次 {n}:n次 {n,m}:n~m次 優先順序:  1. \ 2. () (?=)..[] 3. *+? {n,m} 4.^$ 5. |  範例1:取出夾在S1與S2字串中間的文字 /stexh/H000499?pa=000242102131000499&p_cate=all 欲取出:H000499?pa=000242102131000499 stringpattern=@"(?<=\/stexh\/)(.*)(?=&p_cate=all)"; Matchmatch=Regex.Match(categoryUrl,pattern);  if(match.Success)  {          Groupg=match.Groups[0];           categoryID=g.ToString(); } 範例2:取出金額數字 9折:特價100元 ///

///傳入:strPrice=售價:100.00元 ///傳入:strPrice=建議售價:1,280 ///測試by:https://regex101.com/r/I1LEwC/2 ///預設抓最後一個價格 /// /// ///false /// publicstaticdecimalRegexPrice(stringstrOriPrice,boolfirstPrice=false) { decimalprice; stringstrPrice; strPrice=Regex.Replace(strOriPrice,",",""); //抓最後一個價格 MatchCollectionmatches=Regex.Matches(strPrice,@"\d+([.]\d+)?"); intcount=0; foreach(Matchmatchinmatches) { strPrice=match.Value; if(strPrice!="") { count++; if((count==1)&&(firstPrice)) { break; } } } decimal.TryParse(strPrice,outprice); returnprice; } 範例3: 移除html   publicstaticstringRegexNoHtml(thisstringoriginalString) { stringregex=@"(<.>| )"; varresult=Regex.Replace(originalString,regex,"").Trim(); returnresult; }   .NETRegex 回首頁



請為這篇文章評分?