2011-10-11 11 views
23

Ho ottenuto questo codice per ottenere l'id youtube dai link come www.youtube.com/watch?v=xxxxxxxottenere l'id youtube da un collegamento

URL youtubeURL = new URL(link); 
    youtubeURL.getQuery(); 

fondamentalmente questo mi otterrà l'id facilmente v = xxxxxxxx

ma ho notato qualche link di YouTube saranno come questo

http://gdata.youtube.com/feeds/api/videos/xxxxxx 

sto ottenendo i collegamenti da un feed quindi ho bisogno di costruire una regex per questo o c'è un parser per ottenerlo?

+0

Si consiglia di esaminare [la risposta a una domanda molto simile] (http://stackoverflow.com/questions/5830387/php-regex-find-all-youtube-video-ids-in-string/5831191 # 5.831.191). Estrae il video-id da una varietà di formati di URL di YouTube. – ridgerunner

+0

@ridgerunner ringrazia ma manca i link gdata – Peril

+0

Grazie per averlo indicato. Ho aggiornato [la mia espressione di corrispondenza ID YouTube] (http://stackoverflow.com/questions/5830387/php-regex-find-all-youtube-video-ids-in-string/5831191#5831191) in modo che sia ora corrisponde correttamente all'esempio del sottodominio 'gdata'. – ridgerunner

risposta

39

provato gli altri, ma non è riuscito nel mio caso - regolata l'espressione regolare per adattarsi per i miei URL

String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*"; 

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

    if(matcher.find()){ 
     return matcher.group(); 
    } 

Questo funziona per: (si potrebbe anche realizzare un lunghezza controllo di sicurezza youtubeid = 11)

http://www.youtube.com/embed/Woq5iX9XQhA?html5=1

http://www.youtube.com/watch?v=384IUU43bfQ

http://gdata.youtube.com/feeds/api/videos/xTmi7zzUa-M&whatever

Woq5iX9XQhA

384IUU43bfQ

xTmi7zzUa-M

+0

Grazie mille così !! – Pkmmte

+3

Non funziona per i collegamenti youtu.be/ID. – Konsumierer

+2

non è bello, ma ecco qua: '' '(? <= Guarda \? V = |/videos/| embed \/| youtu.be \/| \/v \/| watch \? V% 3D | % 2Fvideos% 2F | incorporato% 2F | youtu.be% 2F |% 2Fv% 2F) [^ # \ & \? \ N] * '' ' – kritzikratzi

5

Questa regex farebbe il trucco:

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

Questo significa che stiamo cercando prima per video/ o v= poi cattura tutti i seguenti caratteri che possono essere in parola (lettere, cifre e underscore) e trattini.

Esempio in Java:

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()); 
    } 
} 

uscita:

xTmi7zzUa-M 
+0

questo non mi dà l'id solo – Peril

+0

Usando 'http: // gdata.youtube.com/feeds/api/videos/xxxxxx' come indata ottengo' xTmi7zzUa-M' come output. Ho erroneamente letto la tua domanda e stavi chiedendo un'espressione regolare che ti consentisse di analizzare sia 'v = xxxxxxxx' che l'altra? – Marcus

+0

Beh, in realtà. Quella regex funziona in entrambi i casi. Che risultato ottieni? – Marcus

1

Senza conoscere la specifica completa per tutte le possibili URL di YouTube, questo sembra funzionare per gli esempi che hai fornito:

//*EDIT* - fixed to hopefully support more recent youtube link styles/formats: 
(?<=watch\?v=|/videos/|/embed/|youtu.be/)[^&#?]* 

... corrisponde a PjDw3azfZWI da uno di questi URL:

http://www.youtube.com/watch?v=PjDw3azfZWI#t=31m08s 
http://gdata.youtube.com/feeds/api/videos/PjDw3azfZWI 

Si avrebbe bisogno di un po 'di più per ottenere quel particolare informazioni se non si sa che queste erano da youtube, anche se questo è un bel rapido controllo

Tenete presente che se si sta cercando di utilizzare solo il risultato del metodo getQuery(), non sarà possibile estrarre il risultato dall'URL http://gdata.youtube.com/feeds/api/videos/PjDw3azfZWI, poiché questo URL non ha una parte di query ad esso ...

Java Esempio:

Pattern rex = Pattern.compile("(?<=watch\\?v=|/videos/)[^&#]*"); 
Matcher m = rex.matcher(link); 
String YouTubeVideoID = m.group(); 
+0

Non funziona per http://youtu.be/6UW3xuJinEg questo tipo di URL –

+0

@krishan infatti no (che non era nemmeno un URL valido quando è stata posta questa domanda, per quanto ne so ...) ma se sei interessato, questo dovrebbe funzionare per i link 'youtu.be' e'/embed/':' (? <= watch \? v = |/videos/|/embed/| youtu.be /) [^ & # ?] * '(Aggiornerò la mia risposta) - per favore fammi sapere se non lo fa, come l'ho inventato solo ora a mano ... –

+0

ho una soluzione su questa mia domanda http: // stackoverflow. it/questions/25718304/how-to-get-youtube-video-id-da-url-with-java/ –

5
public static String getYoutubeVideoId(String youtubeUrl) 
{ 
String video_id=""; 
    if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) 
{ 

String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; 
CharSequence input = youtubeUrl; 
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); 
Matcher matcher = pattern.matcher(input); 
if (matcher.matches()) 
{ 
String groupIndex1 = matcher.group(7); 
if(groupIndex1!=null && groupIndex1.length()==11) 
video_id = groupIndex1; 
} 
} 
return video_id; 
} 
+0

funziona per me ... –

0

Questo non fa uso di un'espressione regolare, ma deve ancora fare il lavoro.

/** 
* Returns the video id of a YouTube watch link. 
*/ 
public static String getVideoId(String watchLink) 
{ 
    return watchLink.substring(watchLink.length() - 11); 
} 
0
This will work me and simple 

public static String getVideoId(@NonNull String videoUrl) { 
    String reg = "(?:youtube(?:-nocookie)?\\.com\\/(?:[^\\/\\n\\s]+\\/\\S+\\/|(?:v|e(?:mbed)?)\\/|\\S*?[?&]v=)|youtu\\.be\\/)([a-zA-Z0-9_-]{11})"; 
    Pattern pattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE); 
    Matcher matcher = pattern.matcher(videoUrl); 

    if (matcher.find()) 
     return matcher.group(1); 
    return null; 
} 
1

Questo è stato per me ha funzionato

public static String getYoutubeVideoId(String youtubeUrl) { 
    String videoId = ""; 
    if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http")) { 

     String expression = "^.*((youtu.be"+ "/)" + "|(v/)|(/u/w/)|(embed/)|(watch\\?))\\??v?=?([^#&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/; 
     Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE); 
     Matcher matcher = pattern.matcher(youtubeUrl); 
     if (matcher.matches()) { 
      String groupIndex1 = matcher.group(7); 
      if(groupIndex1!=null && groupIndex1.length()==11) 
       videoId = groupIndex1; 
     } 

    } 
    return videoId; 
} 

Fonte link

2

Ottenuto una soluzione migliore da questo link.

Utilizzare il seguente metodo per ottenere il videoId dal collegamento.

YoutubeHelper.java

import com.google.inject.Singleton; 

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

@Singleton 
public class YouTubeHelper { 

    final String youTubeUrlRegEx = "^(https?)?(://)?(www.)?(m.)?((youtube.com)|(youtu.be))/"; 
    final String[] videoIdRegex = { "\\?vi?=([^&]*)","watch\\?.*v=([^&]*)", "(?:embed|vi?)/([^/?]*)", "^([A-Za-z0-9\\-]*)"}; 

    public String extractVideoIdFromUrl(String url) { 
     String youTubeLinkWithoutProtocolAndDomain = youTubeLinkWithoutProtocolAndDomain(url); 

     for(String regex : videoIdRegex) { 
      Pattern compiledPattern = Pattern.compile(regex); 
      Matcher matcher = compiledPattern.matcher(youTubeLinkWithoutProtocolAndDomain); 

      if(matcher.find()){ 
       return matcher.group(1); 
      } 
     } 

     return null; 
    } 

    private String youTubeLinkWithoutProtocolAndDomain(String url) { 
     Pattern compiledPattern = Pattern.compile(youTubeUrlRegEx); 
     Matcher matcher = compiledPattern.matcher(url); 

     if(matcher.find()){ 
      return url.replace(matcher.group(), ""); 
     } 
     return url; 
    } 
} 

Spero che questo aiuti.

Problemi correlati