我正在尝试解析HTTP GET请求以确定该URL是否包含许多文件类型中的任何一种.如果是,我想捕获整个请求.关于ORing我有些不明白的地方.
以下正则表达式仅捕获其中的一部分,并且仅当.flv是ORd值列表中的第一个int时.
(我用空格遮蔽了网址,因为Stackoverflow限制了超链接)
正则表达式:
GET.*?(\.flv)|(\.mp4)|(\.avi).*?
Run Code Online (Sandbox Code Playgroud)
测试文字:
GET http: // foo.server.com/download/0/37/3000016511/.flv?mt=video/xy
Run Code Online (Sandbox Code Playgroud)
匹配输出:
GET http: // foo.server.com/download/0/37/3000016511/.flv
Run Code Online (Sandbox Code Playgroud)
我不明白为什么.*?在正则表达式的末尾不会使它捕获整个文本.如果我摆脱文件类型的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++;
}
Run Code Online (Sandbox Code Playgroud)
}}
你的分组错了.该|需求是在括号内:
GET.*?(\.flv|\.mp4|\.avi).*?
Run Code Online (Sandbox Code Playgroud)
我也不确定你为什么要?在决赛结束时.*?.在大多数语言中,?这里使*非贪婪,所以它匹配尽可能少的字符,而不是阻止模式匹配.在这种情况下,这意味着它不匹配任何字符,因为没有任何字符,所以你可能想删除那个最后的?
GET .*?(\.flv|\.mp4|\.avi).*
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8028 次 |
| 最近记录: |