Extract string from last 2 “/” on a path

拥有回忆 提交于 2019-12-11 18:25:31

问题


I'm trying to extract the last string between two "/"

for example: for this string: https://stackoverflow.com/questions/ask

I want to return "questions"

However, for this string Extract the last substring from a cell

I want to return "6133287"

It has to always be the string in between the last two "/"

I was working with some MID functions I found in this forum, but they were working for things at the beginning of the string. Not necessarily for strings with different lengths.

Thanks, J


回答1:


C# way

public String stringBetweenLastTwoSeparators(String s, String separator){
   String[] result = s.Split(separator.ToCharArray());
   return result[result.Length-2];
} //c#

Below is general logic

    public static String stringBetweenLastTwoSeparators(String s, String separator){
        List<String> result = new List<String>();
        int lastIndexRead = 0;
        bool reading = true;
        while (reading)
        {
            int indexOfSeperator = s.IndexOf(separator,lastIndexRead);
            if (indexOfSeperator != -1)
            {
                result.Add(s.Substring(lastIndexRead, indexOfSeperator-lastIndexRead));
                lastIndexRead = indexOfSeperator + 1;
            }
            else
            {
                result.Add(s.Substring(lastIndexRead, s.Length - lastIndexRead));
                reading = false;
            }
        }
        return result[result.Count - 2];

    }



回答2:


$re = "/\\/([^\\/]+)(?=\\/[^\\/]+\\/?$)/"; 
$str = "https://stackoverflow.com/questions/ask"; 

preg_match($re, $str, $matches);


来源:https://stackoverflow.com/questions/26393156/extract-string-from-last-2-on-a-path

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!