正则表达式或/或不匹配所有内容

时间:2010-04-27 18:09:41

标签: java regex

我正在尝试解析HTTP GET请求以确定该url是否包含许多文件类型中的任何一种。如果是,我想捕获整个请求。关于ORing,我有些不明白的事情。

以下正则表达式仅捕获其中的一部分,并且仅当.flv是ORd值列表中的第一个int时。

(我用空格遮蔽了网址,因为Stackoverflow限制了超链接)

正则表达式:

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

我不明白为什么。*?在正则表达式的末尾不会使它捕获整个文本。如果我摆脱文件类型的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++;
  }

} }

2 个答案:

答案 0 :(得分:6)

你的分组错了。 |需要在括号内:

GET.*?(\.flv|\.mp4|\.avi).*?

我也不确定为什么在最后?结尾处有.*?。在大多数语言中,?这里使*非贪婪,所以它匹配尽可能少的字符,而不是阻止模式匹配。在这种情况下,这意味着它不匹配任何字符,因为没有任何字符,所以你可能想删除那个最后的?。

GET .*?(\.flv|\.mp4|\.avi).*

答案 1 :(得分:0)

首先,你的正则表达式如下:

GET.*?(\.flv)  |  (\.mp4)  |  (\.avi).*?

(为清晰起见添加了空格)。试试这样:

GET.*?(\.flv|\.mp4|\.avi).*?
相关问题