简单的正则表达式来替换 URL 的第一部分 [英] Simple regex to replace first part of URL

查看:43
本文介绍了简单的正则表达式来替换 URL 的第一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定

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

如何选择 /something 之前的任何内容并将其替换为 staticpages?

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

输入 URL 是 request.referer 的结果,但由于你不能 render request.referer(而且我不想要 redirect_to),我正在尝试使用 controller/action 手动构建适当的模板,其中 action 始终是路由,我只需要替换域使用控制器 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.

推荐答案

你可以使用这样的正则表达式:

You could use a regex like this:

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

工作演示

正如您在替换部分中看到的,您可以使用捕获组并连接您想要生成所需网址的字符串.

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

正则表达式的思路是捕获域前后的字符串,使用\1 + staticpages + \3.

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

如果您想将协议更改为 ftp,您可以使用捕获组索引并使用此替换字符串:

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

ftp://\2\3

所以,你会:

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

这篇关于简单的正则表达式来替换 URL 的第一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆