代码之家  ›  专栏  ›  技术社区  ›  user1447679

如何从没有可选查询字符串参数的URL获取路径或slug

  •  1
  • user1447679  · 技术社区  · 7 年前

    在以下URL示例中:

    http://something.com/hello/world/this-is-a-slug
    http://something.com/hello/world/this-is-a-slug#awesome           
    http://something.com/hello/world/this-is-a-slug?awesome=yes#world
    /hello/world/this-is-a-slug
    etc
    

    我需要 this-is-a-slug

    以下是我目前所掌握的,当查询字符串出现时可以使用的:

    [^/]+?(.?(?=[\?]))
    

    但当查询字符串不存在时,无法正确处理此问题。我可以让它工作,但然后用查询字符串打断它。这必须是正则表达式,没有其他方法。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Paolo    7 年前

    可以使用表达式:

    (?<=\/)[a-z-]+(?=[#a-z?=]+$|$)
    
    • (?<=\/) 积极寻找 / .
    • [a-z-]+ 字母字符和 - .
    • (?=[#a-z?=]+$|$) 对字符串结尾或任何字符(如 # , ? , = 以及字符串末尾的字母字符。

    试试看 here .