簡體   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