天天看点

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倍