问题
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