2017-07-18 146 views
0

我試圖創建一個正則表達式從我的域名相匹配的網址,但將排除以下三個URL:正則表達式來排除特定的網址

  • www.mydomain.com/
  • www.mydomain。 COM /接觸
  • www.mydomain.com/about

正則表達式也應該,如果他們有查詢參數排除這些URL。我正在努力解決這個問題,任何幫助表示讚賞。

我曾嘗試非常相似,RIZWAN貼的東西,但你可以看到,這一個允許某些URL應該被排除在外(如測試/ www.mydomain.com /)

我也曾嘗試採用負向前看符號,但沒有得到很遠,與....這是像

^(www.mydomain.com)?\/(?!.*(about|contact)).*$ 

+1

你目前的正則表達式? – anubhava

+1

請顯示你到目前爲止所嘗試的內容,以便我們能夠理解你所面臨的困難。 – arkascha

+0

[我如何問一個好問題?](https://stackoverflow.com/help/how-to-ask) –

回答

0

使用負前瞻:

url = "www.mydomain.com/contact?name=John"; 
 
result = url.match(/^www\.mydomain\.com\/(?!about$|about\?|contact$|contact\?|\?|$).*/); 
 
console.log(result);

字符串開始www.mydomain.com/將匹配,如果後面沒有aboutcontact?,行尾($)和可選的查詢字符串。

或避免重複在交替:

url = "www.mydomain.com/"; 
 
result = url.match(/^www\.mydomain\.com\/(?!(?=(?:about|contact)?(?=\?|$))).*/); 
 
console.log(result);

+0

這似乎起作用,至少對於我的目的!謝謝SLePort,你是我的英雄! – Connemara1

0

正則表達式一般不解析或檢查網址的最佳途徑。您應該使用URL對象來分析位置,但如果條件是特定的,則對單個主機和路徑名部分使用正則表達式可能仍有幫助。例如:

const outputDiv = document.getElementById('output'); 
 
let output = ''; 
 
const urls = [ 
 
    'http://includeddomain.com/blarg', 
 
    'http://includeddomain.com/blarg/anotherblarg', 
 
    'http://includeddomain.com/about/otherstuff/', 
 
    'http://www.includeddomain.com/blarg2', 
 
    'http://subdomain2.includeddomain.com/blarg2/included', 
 
    'http://includeddomain.com/contact', 
 
    'http://includeddomain.com/about/', 
 
    'http://anotherdomain.com/stuff', 
 
].forEach(url => { 
 
    const loc = new URL(url); 
 
    const included = (
 
    loc.host.match(/(.*\.?)includeddomain.com/) && 
 
    ! loc.pathname.match(/(about|contact)(\/?)$/) 
 
); 
 
    output += `<br>${loc.toString()} - ${included ? 'INCLUDED' : 'EXCLUDED'}`; 
 
}); 
 

 
outputDiv.innerHTML = output;
div { 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: start; 
 
}
<div id="output"></div>