2010-06-25 105 views
1

我試圖將其中通配符的網址與實際網址進行匹配。例如:與通配符匹配的網址

http://*google.com/* 

需要匹配

http://maps.google.com 

而且

http://www.google.com/maps 

會是什麼要對這個最好的方法?

我試過使用正則表達式,並且在我手動編程時正常工作,但我不確定是否可以動態生成正則表達式,或者如果這將是這種情況下的最佳做法。

/(http|https):\/\/.*\.?google\.com\/?.*/i 

非常感謝。

+0

WATCHOUT的問題,指出了@Sjoerd – Amarghosh 2010-06-25 11:24:51

+0

什麼是您的解決方案,這一點,@ SAM-投球手? – 2015-09-13 14:57:37

回答

1

[^ ]*替換所有出現的* - 它匹配零個或多個非空格字符序列。

因此http://*google.com/*將成爲http://[^ ]*google.com/[^ ]*

這裏是一個正則表達式做任務:

regex = urlPattern.replace(/\*/g, "[^ ]*"); 
+3

這可能會受到 http://www.mydomain.com/google.com/bla的影響 – Asaf 2012-08-18 21:46:23

3

生成一個正則表達式可能是正確的做法,但得到比簡單地替換星號更復雜。

例如,您的圖案http://*google.com/*不應匹配http://www.malicioushacker.org/1337/google.com/maps

2

如果你想看到一個經過良好測試的庫來提取部分URI,我會檢查一下Google Closure Library的goog.uri.utils方法。

https://github.com/google/closure-library/blob/8e44fb343fff467938f9476ba7f727c6acac76d8/closure/goog/uri/utils.js#L187

下面是做繁重的正則表達式:

goog.uri.utils.splitRe_ = new RegExp(
    '^' + 
    '(?:' + 
     '([^:/?#.]+)' +      // scheme - ignore special characters 
              // used by other URL parts such as :, 
              // ?, /, #, and . 
    ':)?' + 
    '(?://' + 
     '(?:([^/?#]*)@)?' +     // userInfo 
     '([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters, 
              // digits, dashes, dots, percent 
              // escapes, and unicode characters. 
     '(?::([0-9]+))?' +     // port 
    ')?' + 
    '([^?#]+)?' +       // path 
    '(?:\\?([^#]*))?' +     // query 
    '(?:#(.*))?' +      // fragment 
    '$');