2017-05-14 63 views
0

我試圖用正則表達式,以便取回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包含「/」或和字符串的其餘部分。

有沒有什麼好的方法來使用正則表達式?

謝謝!

回答

1

這應該適合你。注意逃脫/(斜槓)

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

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

有關詳細信息,還檢查JAVA代碼生成器。

+0

感謝。但問我知道你不必逃避斜線,我說得對嗎? – idogo

+0

取決於您使用的編程語言或工具。正如我所說的:檢查代碼生成器,瞭解有關在JAVA代碼中執行此操作的正確方法的詳細信息。 – Doqnach

+0

它可以與java解析器一起使用,也可以不經過它們。 – jj27

0

如果你非常肯定的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 
0

你可以使用此正則表達式\/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