Get only URI segments from URL

前端 未结 1 1871
谎友^
谎友^ 2021-01-26 02:01

I am trying to get the URI segments using regular expression.

Example URI:

http://abc.com/hello/hi/bye?humm/ok         


        
相关标签:
1条回答
  • 2021-01-26 02:15

    You forgot to escape the second ? in the second regex. It should read:

    /(?<!\?.+)(?<=\/)[\w-]+(?=(\/|$|\r|\?))/g

    Note: You could improve the regex by using character classes like so:

    /(?<!\?.+)(?<=\/)[\w-]+(?=[/\r\n?]|$)/g

    EDIT:

    For a lowest common denominator solution to cater for all the different flavours of regex, you need a two step process:

    • Remove the trailing ? and all following chars (if it exists):


      ^[^/]+//[^/]+([^?]+)

      Keep the string returned in capture group 1.

    • Extract the URI segments by looping through:


      /([\w-]+)

      The segments are returned in capture group 1.

    0 讨论(0)
提交回复
热议问题