抓取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;
            }
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM