Simple regex to replace first part of URL

2019-09-17 10:05发布

Given

  • http://localhost:3000/something
  • http://www.domainname.com/something
  • https://domainname.com/something

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.

1条回答
男人必须洒脱
2楼-- · 2019-09-17 10:51

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
查看更多
登录 后发表回答