在c#中使用正則表達式進行匹配,有時候我們會遇到這種情況,cpu使用率100%, 但是正則表達式并沒有異常拋出,正則一直處于匹配過程中,這將導致系統資源被耗盡, 應用程序被卡住,這是由于正則不完全匹配,而且Regex中沒有Timeout屬性,使正則處 理器陷入了死循環。 public static Match GetMatchRigid(string input, string pattern, string find) { string _pattn = Regex.Escape(pattern); _pattn = _pattn.Replace(@"\[變量]", @"[\s\S]*?"); if (Regex.Match(pattern.TrimEnd(), Regex.Escape(find) + "$", RegexOptions.Compiled).Success) _pattn = _pattn.Replace(@"\" + find, @"(? <TARGET>[\s\S]+)"); else _pattn = _pattn.Replace(@"\" + find, @"(? <TARGET>[\s\S]+?)"); Regex r = new Regex(_pattn, RegexOptions.IgnoreCase | RegexOptions.Compiled); Match m = r.Match(input); return m; }
- 2 回答
- 0 關注
- 373 瀏覽
添加回答
舉報
0/150
提交
取消