2

Lets suppose I have a url like this:

https://www.youtube.com/watch/3e4345?v=rwmEkvPBG1s

What is the best and shorthest way to only get the 3e4345 part? Sometimes it doesn't contain additional params in ? I don't want to use any gems.

What I did was:

    url =  url.split('/watch/')
    url =  url[1].split('/')[0].split('?')[0]

Is there a better way? Thanks

John Smith
  • 6,105
  • 16
  • 58
  • 109

3 Answers3

1

You could do the following and using the match function to find a match based on a regular expression statement. The value at [1] is the first capture from the regular expression. I have included a breakdown from regexper.com to help illustrate what the expression is accomplishing.

You will notice parentheses around the \d+ which are what captures the digits out of the URL when it matches.

url.to_s.match(/\/watch\/(\d+).*$/)[1]

Regexper

Chris
  • 788
  • 4
  • 11
  • 1
    Perfect but the code can be also a string. But the code ends with `/` or `?` or with nothing for sure. So it could be: `wer34/hello` or `wer34/` or `wer34?locale=3` or `wer34`. Thanks for your help! – John Smith Mar 11 '15 at 22:06
1

possibly the safest and best one. use URI.

URI("https://www.youtube.com/watch/34345?v=rwmEkvPBG1s").path.split("/").last

For more refer How to extract URL parameters from a URL with Ruby or Rails?

Community
  • 1
  • 1
Paritosh Piplewar
  • 7,982
  • 5
  • 26
  • 41
1
x = "https://www.youtube.com/watch/34345?v=rwmEkvPBG1s"
File.basename(URI(x).path)
=> "34345"
Mori
  • 27,279
  • 10
  • 68
  • 73