抓取2个字符串中间的字符串




        class MidString {

            //有异常发生!
            /// <summary>
            /// 搜索字符串
            /// </summary>
            /// <param name="source">目标字符串</param>
            /// <param name="start">之前字符串</param>
            /// <param name="end">之后字符串</param>
            /// <returns>获取两个字符串中间的字符串</returns>
            public static string Find(string source, string start, string end) {    //获取搜索到的数目  
                try {
                    int i, j;
                    // startIndex 小于 0(零)或大于此字符串的长度
                    //   public int IndexOf(String value, int startIndex);
                    i = source.IndexOf(start, 0) + start.Length;   //开始位置  
                    j = source.IndexOf(end, i);        //结束位置    
                    return source.Substring(i, j - i);       //取搜索的条数,用结束的位置-开始的位置,并返回    
                }
                catch {
                    return " ";
                }
            }

            public static string Find_3(string source, string start, string end) {
                int x = source.IndexOf(start);
                if (x < 0) //找不到返回空
                    return "";
                int y = source.IndexOf(end, x + start.Length); //从找到的第1个字符串后再去找
                if (y < 0) //找不到返回空
                    return "";
                return source.Substring(x + start.Length, y - x - start.Length);
            }

            public static string Find_4(string sourse, string start, string end) {
                string result = string.Empty;
                int x, y;
                try {
                    x = sourse.IndexOf(start);
                    if (x == -1)
                        return result;
                    string z = sourse.Substring(x + start.Length);
                    y = z.IndexOf(end);
                    if (y == -1)
                        return result;
                    result = z.Remove(y);
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
                return result;
            }

            public static string RegexFind(string sourse, string start, string end) {
                Regex rg = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
                return rg.Match(sourse).Value;
            }

            /// <summary>
            /// 转换成一行
            /// </summary>
            /// <param name="sText"></param>
            /// <returns></returns>
            public static string ReplaceWhiteString(string sText) {
                sText = sText.Replace("\r", "");
                sText = sText.Replace("\n", "");
                sText = sText.Replace("\t", "");
                sText = sText.Replace(" ", "");
                return sText;
            }
        }

猜你喜欢

转载自www.cnblogs.com/xe2011/p/12116390.html