james
james

Reputation: 4049

Simple regex to replace first part of URL

Given

How do I select whatever is before the /something and replace it with staticpages?

The input URL is the result of a request.referer, but since you can't render request.referer (and I don't want a redirect_to), I'm trying to manually construct the appropriate template using controller/action where action is always the route, and I just need to replace the domain with the controller staticpages.

Upvotes: 0

Views: 2134

Answers (1)

Federico Piazza
Federico Piazza

Reputation: 30985

You could use a regex like this:

(https?://)(.*?)(/.*)

Working demo

enter image description here

As you can see in the Substitution section, you can use capturing group and concatenates the strings you want to generate the needed urls.

The idea of the regex is to capture the string before and after the domain and use \1 + staticpages + \3.

If you want to change the protocol to ftp, you could play with capturing group index and use this replacement string:

ftp://\2\3

So, you would have:

ftp://localhost:3000/something
ftp://www.domainname.com/something
ftp://domainname.com/something

Upvotes: 2

Related Questions