天天看點

C#字元串 - 截取指定字元串的中間串

轉自:https://www.cnblogs.com/jolins/p/9714238.html

寫法有很多,記錄常用的兩種:

1、正規表達式

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

2、利用字元串indexof截取

public static string MidStrEx(string sourse, string startstr, string endstr)
 {
    string result = string.Empty;
    int startindex, endindex;
    try
    {
        startindex = sourse.IndexOf(startstr);
        if (startindex == -1)
            return result;
        string tmpstr = sourse.Substring(startindex + startstr.Length);
        endindex = tmpstr.IndexOf(endstr);
        if (endindex == -1)
            return result;
        result = tmpstr.Remove(endindex);
       }
    catch (Exception ex)
    {
        Console.WriteLine("MidStrEx Err:" + ex.Message);
    }

    return result;
}
           

就效率來說,測試了幾次,方法2比方法1大約快10倍