【问题标题】:Extract string from last 2 "/" on a path从路径上的最后 2 个“/”中提取字符串
【发布时间】:2014-10-15 22:24:39
【问题描述】:

我正在尝试提取两个“/”之间的最后一个字符串

例如: 对于这个字符串: https://stackoverflow.com/questions/ask

我想返回“问题”

但是,对于这个字符串 Extract the last substring from a cell

我要返回“6133287”

它必须始终是最后两个“/”之间的字符串

我正在使用我在这个论坛中找到的一些 MID 函数,但它们正在处理字符串开头的内容。不一定适用于不同长度的字符串。

谢谢, J

【问题讨论】:

  • 首选语言? Windows 还是 Unix 环境?有一百万种方法可以做到这一点......
  • 在“/”上使用拆分函数,然后根据需要对结果数组进行索引。如果它有一个尾随“/”,那么它将是 array[length] 否则 array[length - 1]

标签: extract between


【解决方案1】:

C#方式

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

以下是一般逻辑

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-27
      • 1970-01-01
      • 2017-09-21
      • 2011-12-19
      • 2021-05-29
      相关资源
      最近更新 更多