0

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

Community
  • 1
  • 1
Seacubs17
  • 1
  • 2
  • 1
    prefferred language? Windows or Unix environment? There are a million ways of doing this... – Liviu Chircu Oct 15 '14 at 22:28
  • Use a split function on "/" and then index into the resulting array as needed. If it has a trailing "/" then it will be array[length] otherwise array[length - 1] – TheEdge Oct 15 '14 at 22:31

2 Answers2

0

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];

    }
Zero
  • 1,562
  • 1
  • 13
  • 29
0
$re = "/\\/([^\\/]+)(?=\\/[^\\/]+\\/?$)/"; 
$str = "https://stackoverflow.com/questions/ask"; 

preg_match($re, $str, $matches);
Sasha
  • 171
  • 1
  • 7