Thermatix
Thermatix

Reputation: 2929

regex to catch everything but the first segment of a URL

Assuming I have the following URL: /members/some/path/route

I want a regex that will return only /some/path/route

So far I have [^\/]\/.*

But that doesn't quite work as it returns s/some/path/route

Can someone give me a hand here? I'd also like it if someone can tell me why my regex doesn't quite work so I can learn why it doesn't work.

I'm using ruby.

Upvotes: 1

Views: 372

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110685

I would not use a regex for this. Instead I would use Pathname#each_filename to construct an array whose elements are each component of the path.

str = "/members/some/path/route"

require "pathname"

Pathname(str).each_filename.to_a[1..-1].join('/')
  #=> "some/path/route"

We see that:

Pathname(str).each_filename.to_a[1..-1]
  #=> ["members", "some", "path", "route"]

This uses the class method Kernel::Pathname. I don't find the doc for that (which would be with the docs for Object), but we can verify:

method(:Pathname).owner
  #=> Kernel

This is similar to the class methods Kernel::Array, Kernel::String and others:

Array(21)   # => [21]
String(19)  # => "19"

You could instead write:

Pathname.new(str).each_filename.to_a[1..-1].join('/')
  #=> "some/path/route"

Upvotes: 0

Saleem
Saleem

Reputation: 8978

Assuming you are using javascript:

your regex will be

result = url.match(/(?:\/.*?)(\/.*)/g);

and your expected string will be held in result[1]

If using RUBY

if url =~ /(?:\/.*?)(\/.*)/
    result = $~[1]
end

OR

regexp = /(?:\/.*?)(\/.*)/
match = regexp.match(url)
if match
    result = match[1]
else
    result = ""
end

Upvotes: 1

ahmetunal
ahmetunal

Reputation: 3960

You need to find the second "/" and take the rest

preg_match("/\/(.*?)(\/.*)/", $url, $preg);
print_r($preg);

returns

Array
(
    [0] => /members/some/path/route
    [1] => members
    [2] => /some/path/route
)

But, I recommend not using RegExp, since it is a simple string, an explode() function would do

$path_array = array_slice(explode("/", $url), 2); // we are slicing at 2, because there is a leading '/' at the beginning
$new_path = "/".implode("/", $path_array);
echo $new_path;

Upvotes: 0

Related Questions