Pages - Menu

2016年5月6日 星期五

C# regex 正規表示法,懶人版

最近又需要正規表示法,查了之後才發現,要寫一長串阿…
寫成function方便使用。前面丟『來源字串』,後面丟『規則』。
回傳List<string>。
可使用toArray 轉成陣列後,假如前後有『, 』,可使用 trim(‘,') ,將前後的『,』刪除。




public static List<string> regexMatch(string source,string pattern)
        {
            Regex r = new Regex(pattern,RegexOptions.IgnoreCase);
            List<string> result = new List<string>();
            MatchCollection _Collection = r.Matches(source);
            foreach (Match matchs in _Collection)
            {
                result.Add(matchs.Value);
                 // Group的內容
                //GroupCollection groups = matchs.Groups;
                //foreach (var groupValue in groups)
                //{
                //    result.Add(groupValue.ToString());
                //}
            }

沒有留言:

張貼留言