Get snippet of a String with regular expression

2

In the code there is a string that contains HTML. Within this HTML there is embed of a YouTube video:

<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" src="http://www.youtube.com/v/ZJLAJVmggt0%26hl=en%26fs=1%26rel=0%26ap=%2526fmt=18"width="725" height="400"></embed>

I need to get only the YouTube video ID, which in the above case would be ZJLAJVmggt0 .

How to do this knowing that the string is within one iteration, ie each cycle changes the value, so the above is never in the same position within the string and the video ID is different each time iteration.

    
asked by anonymous 25.09.2017 / 12:13

3 answers

0

I found a answer in SOen:

Using regular expression .*youtube.com/./(.*?)%.* with Matcher :

Example:

String mydata = "<STRING_COM_O_CODIGO_EMBED_DO_YOUTUBE>";
Pattern pattern = Pattern.compile(".*youtube.com/./(.*?)%.*");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}
    
26.09.2017 / 22:43
0
var t = .... ;
var id = t.replace(/.*youtube.com\/.\/(.*?)%.*/, '$1');
console.log(id);

EDIT: Ooops: wrong Java ...

String id = t.replaceAll(".*youtube.com/./(.*?)%.*","$1")
    
25.09.2017 / 12:35
0

I think the code below will do what you need:

String mydata = "<embed type=\"application/x-shockwave-flash\" pluginspage=\"http://www.macromedia.com/go/getflashplayer\" src=\"http://www.youtube.com/v/ZJLAJVmggt0%26hl=en%26fs=1%26rel=0%26ap=%2526fmt=18\" width=\"725\" height=\"400\"></embed>";
Pattern pattern = Pattern.compile("(?<=youtube.com/v/)(.*?)(?=\%)");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Input:

<embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" src="http://www.youtube.com/v/ZJLAJVmggt0%26hl=en%26fs=1%26rel=0%26ap=%2526fmt=18"width="725" height="400"></embed>

REGEX:

(?<=youtube.com/v/)(.*?)(?=\%)

Output:

ZJLAJVmggt0
    
27.09.2017 / 03:57