我想分析一個HTTP GET請求來確定url是否包含任何數量的文件類型。如果是這樣,我想捕獲整個請求。有些東西我不懂ORing。正則表達式/或不匹配所有內容
以下正則表達式僅捕獲其中的一部分,並且僅當.flv是ORd值列表中的第一個整數時才適用。
(我模糊的URL與空間,因爲限制了#1的超鏈接)
正則表達式:
GET.*?(\.flv)|(\.mp4)|(\.avi).*?
測試文本:
GET http: // foo.server.com/download/0/37/3000016511/.flv?mt=video/xy
匹配輸出:
GET http: // foo.server.com/download/0/37/3000016511/.flv
我d不明白爲什麼。*?在正則表達式的最後並沒有調用它來捕獲整個文本。如果我擺脫了文件類型的ORing,那麼它就可以工作。
下面是測試代碼的情況下,我的解釋是沒有意義的:
public static void main(String[] args) {
// TODO Auto-generated method stub
String sourcestring = "GET http: // foo.server.com/download/0/37/3000016511/.flv?mt=video/xy";
Pattern re = Pattern.compile("GET .*?\\.flv.*"); // this works
//output:
// [0][0] = GET http :// foo.server.com/download/0/37/3000016511/.flv?mt=video/xy
// the match from the following ends with the ".flv", not the entire url.
// also it only works if .flv is the first of the 3 ORd options
//Pattern re = Pattern.compile("GET .*?(\\.flv)|(\\.mp4)|(\\.avi).*?");
// output:
//[0][0] = GET http: // foo.server.com/download/0/37/3000016511/.flv
// [0][1] = .flv
// [0][2] = null
// [0][3] = null
Matcher m = re.matcher(sourcestring);
int mIdx = 0;
while (m.find()){
for(int groupIdx = 0; groupIdx < m.groupCount()+1; groupIdx++){
System.out.println("[" + mIdx + "][" + groupIdx + "] = " + m.group(groupIdx));
}
mIdx++;
}
}}
+1。將一個不情願的量詞作爲正則表達式中的最後一件事是毫無意義的。在這種情況下並不重要;由於錯誤的分組,正則表達式的那部分從來沒有達到過。 – 2010-04-27 19:26:35
我可能以此開始。無論如何,我嘗試過,現在沒有匹配,無論是在myregextester點com或在java代碼。 – user327105 2010-04-27 21:41:21
嗯,它適用於我在myregextester.com,源文本「GET http:// foo.server.com/download/0/37/3000016511/.flv?mt=video/xy」(與周圍的空間//刪除)和正則表達式「GET。*?(\。flv | \ .mp4 | \ .avi)。*」。我得到了兩個組,一個是整個字符串,另一個只包含擴展名。 – 2010-04-28 08:28:01