繁体   English   中英

使用正则表达式从 url 中删除主机名和端口

[英]remove hostname and port from url using regular expression

我正在尝试删除

http://localhost:7001/

http://localhost:7001/www.facebook.com

得到 output 作为

www.facebook.com

我可以用来实现这个确切模式的正则表达式是什么?

您不需要任何库或正则表达式

var url = new URL('http://localhost:7001/www.facebook.com')
console.log(url.pathname)

https://developer.mozilla.org/en-US/docs/Web/API/URL

对于javascript,您可以使用以下代码:

var URL = "http://localhost:7001/www.facebook.com";
var newURL = URL.replace (/^[a-z]{4,5}\:\/{2}[a-z]{1,}\:[0-9]{1,4}.(.*)/, '$1'); // http or https
alert (newURL);

看看这个代码在行动这里

问候, 维克多

基于@atiruz 的回答,但这是

url = url.replace( /^[a-zA-Z]{3,5}\:\/{2}[a-zA-Z0-9_.:-]+\//, '' );
  • 最短的
  • 也可以使用 https 或 ftp
  • 可以带或不带显式端口的 url

这就是我在不诉诸正则表达式的情况下使其工作的方式:

var URL = "http://localhost:7001/www.facebook.com";

var URLsplit = URL.split('/');

var host = URLsplit[0] + "//" + URLsplit[2] + "/";

var newURL = URL.replace(host, '');

虽然可能不是一个优雅的解决方案,但对于那些没有太多正则表达式经验的人来说应该更容易理解(像我一样!呃!)。

对于匹配任何协议、域和(可选)端口的简单正则表达式:

var url = 'http://localhost:7001/www.facebook.com';

// Create a regex to match protocol, domain, and host
var matchProtocolDomainHost = /^.*\/\/[^\/]+:?[0-9]?\//i;

// Replace protocol, domain and host from url, assign to `myNewUrl`
var myNewUrl = url.replace(matchProtocolDomainHost, '');

现在myNewUrl === 'www.facebook.com'

参见regex101 上的演示

或者,您可以使用as3corelibURI 类解析 url。 这样您就不必进行任何字符串操作,这有助于避免做出无意的假设。 它需要更多的代码行,但它是一个更通用的解决方案,应该适用于各种情况:

var url : URI = new URI("http://localhost:7001/myPath?myQuery=value#myFragment");

// example of useful properties
trace(url.scheme); // prints: http
trace(url.authority); // prints the host: localhost
trace(url.port); // prints: 7001
trace(url.path); // prints: /myPath
trace(url.query); // prints: myQuery=test
trace(url.fragment); // prints: myFragment

// build a new relative url, make sure we keep the query and fragment
var relativeURL : URI = new URI();
relativeURL.path = url.path;
relativeURL.query = url.query;
relativeURL.fragment = url.fragment;

var relativeURLString : String = relativeURL.toString();

// remove first / if any
if (relativeURLString.charAt(0) == "/") {
    relativeURLString = relativeURLString.substring(1, relativeURLString.length);
}

trace(relativeURLString); // prints: myPath?myQuery=test#myFragment

这里的所有其他正则表达式看起来都有点复杂吗? 这就是所需要的:(对吗?)

var originSlash = /^https?:\/\/[^/]+\//i;

theUrl.replace(originSlash, '');

您可以不使用正则表达式,而是使用浏览器解析 URL 的功能:

var parser = document.createElement('a');
parser.href = "http://localhost:7001/www.facebook.com";
var path = parser.pathname.substring(1); // --> results in 'www.facebook.com'

正则表达式匹配要删除的 url 部分,将类似于:/ /^http[s]?:\\/\\/.+?\\// : /^http[s]?:\\/\\/.+?\\//

Java 代码示例(请注意,在 Java 中我们使用两个反斜杠“\\\\”来转义字符):

String urlWithBasePath = "http://localhost:7001/www.facebook.com";
String resultUrl = urlWithBasePath.replaceFirst("^http[s]?:\\/\\/.+?\\/", ""); // resultUrl => www.facebook.com

JS代码示例:

let urlWithBasePath = "http://localhost:7001/www.facebook.com";
let resultUrl = urlWithBasePath.replace(/^http[s]?:\/\/.+?\//, ''); // resultUrl => www.facebook.com

Python代码示例:

import re
urlWithBasePath = "http://localhost:7001/www.facebook.com"
resultUrl = re.sub(r'^http[s]?:\/\/.+?\/', '', urlWithBasePath) # resultUrl => www.facebook.com

示例或 Ruby 代码:

urlWithBasePath = "http://localhost:7001/www.facebook.com"
resultUrl =  urlWithBasePath = urlWithBasePath.sub(/^http[s]?:\/\/.+?\//, '') # resultUrl => www.facebook.com

PHP代码示例:

$urlWithBasePath = "http://localhost:7001/www.facebook.com";
$resultUrl = preg_replace('/^http[s]?:\/\/.+?\//', '', $urlWithBasePath); // resultUrl => www.facebook.com

C# 代码示例(您还应该using System.Text.RegularExpressions;指定):

string urlWithBasePath = "http://localhost:7001/www.facebook.com";
string resultUrl = Regex.Replace(urlWithBasePath, @"^http[s]?:\/\/.+?\/", ""); // resultUrl => www.facebook.com

如果您只是想删除原点并获取 URL 的 rest,包括哈希、查询参数和任何不受限制的字符:

 function getUrlFromPath(targetUrl) { const url = new URL(targetUrl); return targetUrl.replace(url.origin, ''); } function main() { const testUrls = [ 'http://localhost:3000/test?search=something', 'https://www.google.co.in/search?q=hello+there+obi+wan&newwindow=1&sxsrf=ALiCzsZoaZvs0CrLQEHFmmR-MdrZ2ZHW2A%3A1665462761920&source=hp&ei=6fFEY_7cNY36wAOFyqagBA&iflsig=AJiK0e8AAAAAY0T_-R12vR7P_tmmkpEqgzmoZNczbnZA&ved=0ahUKEwi-9buirNf6AhUNPXAKHQWlCUQQ4dUDCAc&uact=5&oq=hello+there+obi+wan&gs_lcp=Cgdnd3Mtd2l6EAMyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEMgUIABCABDIFCAAQgAQyBQgAEIAEOgQIIxAnOhEILhCABBCxAxCDARDHARDRAzoLCAAQgAQQsQMQgwE6CwguEIAEELEDEIMBOg4ILhCABBCxAxCDARDUAjoICAAQsQMQgwE6CwguEIAEELEDENQCOggIABCABBCxAzoICC4QsQMQgwFQAFjjE2C6FmgAcAB4A4AB1QSIAd8ZkgELMC45LjIuMC4yLjGYAQCgAQE&sclient=gws-wiz' ]; testUrls.forEach(url => { console.log(getUrlFromPath(url)); }); } main();

实现此目的的故障安全正则表达式模式将变得复杂且麻烦。

只需使用替换

"http://localhost:7001/www.facebook.com".replace("http://localhost:7001/",'')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM