写法有很多,记录常用的两种:
1、正则表达式
1 public static string MidStrEx_New(string sourse, string startstr, string endstr) 2 { 3 Regex rg = new Regex("(?<=(" + startstr + "))[.\s\S]*?(?=(" + endstr + "))", RegexOptions.Multiline | RegexOptions.Singleline); 4 return rg.Match(sourse).Value; 5 }
2、利用字符串indexof截取:
1 public static string MidStrEx(string sourse, string startstr, string endstr) 2 { 3 string result = string.Empty; 4 int startindex, endindex; 5 try 6 { 7 startindex = sourse.IndexOf(startstr); 8 if (startindex == -1) 9 return result; 10 string tmpstr = sourse.Substring(startindex + startstr.Length); 11 endindex = tmpstr.IndexOf(endstr); 12 if (endindex == -1) 13 return result; 14 result = tmpstr.Remove(endindex); 15 } 16 catch (Exception ex) 17 { 18 Log.WriteLog("MidStrEx Err:" + ex.Message); 19 } 20 return result; 21 }
就效率来说,测试了几次,方法2比方法1大约快10倍