2016-11-15 147 views
1

我當前的URL:正則表達式匹配的URL

ristoranti/location/latvia/riga/other-tag 

我需要一個正則表達式沒有得到URL如果有location

這裏是我的嘗試:

ristoranti/(?!location$).*)?(.+?)/(.+?) 

示例url我需要得到:

ristoranti/latvia/riga/other-tag 

我不太擅長正則表達式,但如果我是正確的第一部分除了location,我錯了嗎?

+0

的可能的複製(http://stackoverflow.com/questions/ [什麼是最好的正則表達式來檢查一個字符串是否是一個有效的URL?] 161738/what-is-best-regular-expression-to-check-if-a-string-is-a-valid-url) –

+0

您需要使用簡單的字符串操作從字符串中移除'/ location /' 。或者使用兩個捕獲組,例如'(ristoranti /)[^/]*/(.+?)'並替換爲$ 1 $ 2'。 –

+0

我無法用任何操作移除'/ location /' –

回答

0

問題是$存在於您的負面預測中,將無法阻止ristoranti/location/latvia/riga/other-tag匹配,因爲您的網址並非真正以location結尾。您應該將其替換爲

(?!location/) 

當URL提前有location/時,將會失敗匹配。

還在開始時使用^。因此,最終的正則表達式應該是:

^ristoranti/(?!location/)([^/]*)/([^/]*)/(.*) 

RegEx Demo