1

I have a URL string:

http://ip-address/user/reset/1/1379631719drush/owad_yta75

into which I need to insert a short string:

help after the third occurance of "/" so that the new string will be:

http://ip-address/**help**/user/reset/1/1379631719drush/owad_yta75

I cannot use Ruby's string.insert(#, 'string') since the IP address is not always the same length.

I'm looking at using a regex to do that, but I am not exactly sure how to find the third '/' occurance.

1
  • 1
    Why does it have to be a single regex? Wouldn't it make more sense to chop the URL into pieces with URI or Addressable and then mangle the path component on its own? Commented Mar 10, 2015 at 21:57

3 Answers 3

3

One way to do this:

url = "http://ip-address/user/reset/1/1379631719drush/owad_yta75"
url.split("/").insert(3, 'help').join('/')
# => "http://ip-address/help/user/reset/1/1379631719drush/owad_yta75"
Sign up to request clarification or add additional context in comments.

2 Comments

^ that. do. not. use. regexps. I used regexps only first 2-3 (of approx 17 now) years of my career, just because they looked cool and it was awesome to possess this knowledge. in reality it situations when you probably 'd use regexp to parse/check something - there is library already implemented for you for this task.
actually I lied abit - I'm using them dozens of times per day - when grepping something in emacs e.g. but never ever in code.
2

You can do that with capturing groups using a regex like this:

(.*?//.*?/)(.*)
  ^   ^     ^- Everything after 3rd slash
  |   \- domain
  \- protocol

Working demo

And use the following replacement:

\1help/\2

If you check the Substitution section you can see your expected output

enter image description here

3 Comments

@roland you can find the link in the answer to that example. What I use is regex101.com
I've noticed a downvote, can the downvoter give details about what my answer is not useful?
sorry that was me, hit the wrong icon by mistake. Thanks for the regex link.
2

The thing you're forgetting is that a URL is just a host plus file path to a resource, so you should take advantage of tools designed to work with those. While it'll seem unintuitive at first, in the long run it'll work better.

require 'uri'

url = 'http://ip-address/user/reset/1/1379631719drush/owad_yta75'
uri = URI.parse(url)
path = uri.path # => "/user/reset/1/1379631719drush/owad_yta75"
dirs = path.split('/') # => ["", "user", "reset", "1", "1379631719drush", "owad_yta75"]
uri.path = (dirs[0,1] + ['help'] + dirs[1 .. -1]).join('/')

uri.to_s # => "http://ip-address/help/user/reset/1/1379631719drush/owad_yta75"

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.