Java正则表达式不匹配有效结果

时间:2013-10-06 23:14:31

标签: java regex

我正在尝试编写一个简单的java正则表达式,以从其网址中提取给定YouTube视频的视频ID。例如:

http://www.youtube.com/watch?v=-mzvAAuCo1c

我想提取出来:-mzvAAuCo1c

以下是我正在尝试的内容:

Pattern pattern = Pattern.compile("v=([^&]+)");
String url = "http://www.youtube.com/watch?v=-mzvAAuCo1c";
Matcher matcher = pattern.match(url);
System.out.println(matcher.getGroupCount() ); //outputs 1
System.out.println(matcher.matches() ); //returns false;
System.out.println( matcher.group(0) ); //throws exception, same for 1

我做错了什么?

3 个答案:

答案 0 :(得分:2)

调用find以匹配部分String。拨打matches后不要致电find - 这会产生IllegalStateException。您希望捕获组1而不是0,因为后者会返回完整的String

Pattern pattern = Pattern.compile("v=([^&]+)");
String url = "http://www.youtube.com/watch?v=-mzvAAuCo1c&foo=3";
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
    System.out.println(matcher.groupCount()); 
    System.out.println(matcher.group(1)); 
}

答案 1 :(得分:2)

Matcher matcher = pattern.match(url);
System.out.println(matcher.getGroupCount() ); //outputs 1

首先,上面的两行甚至都没有编译。将它们更改为:

Matcher matcher = pattern.matcher(url);
System.out.println(matcher.groupCount() ); //outputs 1

其次,你的正则表达式:

Pattern pattern = Pattern.compile("v=([^&]+)");

仅匹配部分输入,这就是

的原因
matcher.matches()

返回false。将正则表达式更改为:

Pattern pattern = Pattern.compile(".*v=([^&]+)");

最后,由于matcher.matches()未返回true,因此声明

matcher.group(0)

会抛出异常。

固定代码:

        Pattern pattern = Pattern.compile(".*v=([^&]+)");
        String url = "http://www.youtube.com/watch?v=-mzvAAuCo1c";
        Matcher matcher = pattern.matcher(url);
        System.out.println(matcher.groupCount()); //outputs 1
        System.out.println(matcher.matches()); //returns true;
        System.out.println(matcher.group(1)); //returns -mzvAAuCo1c

答案 2 :(得分:0)

试试这个

(?<=videos\/|v=)([\w-]+)

使用中

public static void main(String[] args) {

String link = "http://gdata.youtube.com/feeds/api/videos/xTmi7zzUa-M&whatever";
String pattern = "(?:videos\\/|v=)([\\w-]+)";

Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(link);

if(matcher.find()){
    System.out.println(matcher.group());
    }
}

找到Here