检索与正则表达式的Java嵌入YouTube视频ID

问题描述:

我试图用正则表达式,以便取回YouTube视频ID(嵌入式)检索与正则表达式的Java嵌入YouTube视频ID

假设下面的网址:

http://www.youtube.com/embed/f0Cn2g8ekMQ/ 
http://www.youtube.com/embed/f0Cn2g8ekMQ// 
http://www.youtube.com/embed/f0Cn2g8ekMQ?param 

我想获得ID“f0Cn2g8ekMQ”。

我试图做这样说:“?”

regex: https?://www\.youtube\.com/embed/(\S+)[/|\?]?.* 

但好像还是运营商不为我工作,我收到的ID包含“/”或和字符串的其余部分。

有没有什么好的方法来使用正则表达式?

谢谢!

这应该适合你。注意逃脱/(斜杠)

/https?:\/\/www\.youtube\.com\/embed\/([^\/?]+)/g

https://regex101.com/r/57JeRU/1

有关详细信息,还检查JAVA代码生成器。

+0

感谢。但问我知道你不必逃避斜线,我说得对吗? – idogo

+0

取决于您使用的编程语言或工具。正如我所说的:检查代码生成器,了解有关在JAVA代码中执行此操作的正确方法的详细信息。 – Doqnach

+0

它可以与java解析器一起使用,也可以不经过它们。 – jj27

如果你非常肯定的URL的结构常是下面要使用的,你可以用这个例子:

try{ 
     String add1 = "http://www.youtube.com/embed/f0Cn2g8ekMQ/"; 
     String add2 = "http://www.youtube.com/embed/f0Cn2g8ekMQ//"; 
     String add3 = "http://www.youtube.com/embed/f0Cn2g8ekMQ?param"; 

     String []all1 = add1.replace("//", "/").split("[/?]"); 
     String []all2 = add2.replace("//", "/").split("[/?]"); 
     String []all3 = add3.replace("//", "/").split("[/?]"); 

     System.out.println(all1[3]); 
     System.out.println(all2[3]); 
     System.out.println(all3[3]); 
    }catch(ArrayIndexOutOfBoundsException e){ 
     System.out.println("URL format changed"); 
     //Do other things here if url structure changes 
    } 

输出

f0Cn2g8ekMQ 
f0Cn2g8ekMQ 
f0Cn2g8ekMQ 

你可以使用此正则表达式\/embed\/(\w+)[\/?]不是你可以得到如下结果:

String[] str = {"http://www.youtube.com/embed/f0Cn2g8ekMQ/", 
    "http://www.youtube.com/embed/f0Cn2g8ekMQ//", 
    "http://www.youtube.com/embed/f0Cn2g8ekMQ?param"}; 

Pattern p = Pattern.compile("\\/embed\\/(\\w+)[\\/?]"); 
Matcher m; 
for (String s : str) { 
    m = p.matcher(s); 
    if (m.find()) { 
     System.out.println(m.group(1)); 
    } 
} 

输出

f0Cn2g8ekMQ 
f0Cn2g8ekMQ 
f0Cn2g8ekMQ 

Ideone demo