0

I have the following strings:

src = "dav://w.lvh.me:3000/Home/Transit/file"
host = "w.lvh.me:3000"

What I want to obtain is "/Home/Transit/file" using those two strings

I thought of searching for host in src and delete it the first time it appears, and everything before it, but I'm not sure exactly how to do that. Or maybe there's a better way?

Any help would be appreciated!

2 Answers 2

8

There is a better way indeed:

require 'uri'
src = "dav://w.lvh.me:3000/Home/Transit/file"
src = URI.parse src

src.path      # => "/Home/Transit/file"

When there are spaces in the string, you must pass extra step of escaping/unescaping. Fortunantly, this is simple:

require 'uri'
src = "dav://w.lvh.me:3000/Home/Transit/Folder 144/webdav_put_request"
src = URI.parse(URL.escape src)

URL.unescape(src.path)      # => "/Home/Transit/Folder 144/webdav_put_request"
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect answer. Not everything should be boiled down to a regular expression. You want a URI parser for parsing URIs, not yet another busted regular expression.
i forgot to ask, what if there are spaces in src ? URI.parse raises an error for example if src = "dav://w.lvh.me:3000/Home/Transit/Folder 144/webdav_put_request"
Thank you. I tried escaping with a custom function but I think it did not escape right. URI.escape works ok!
2

This should do the job:

src = "dav://w.lvh.me:3000/Home/Transit/file"
host = "w.lvh.me:3000"
result = src.sub(/.*#{host}/, '')
#=> "/Home/Transit/file"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.