Get String Snippet with Regular Expression

Asked

Viewed 166 times

2

In the code there is a string that contains HTML. Inside this HTML there is a 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 from this excerpt only the ID of the Youtube video, which in the above case would be the ZJLAJVmggt0.

How to do this knowing that the string is within an iteration, that is, each cycle the variable changes value, so the above snippet is never in the same position within the string and the video ID is different with each iteration.

3 answers

0

var t = .... ;
var id = t.replace(/.*youtube.com\/.\/(.*?)%.*/, '$1');
console.log(id);

EDIT: Ooops: Wrong Java...

String id = t.replaceAll(".*youtube.com/./(.*?)%.*","$1")
  • @Articuno, Ooops, I read wrong... (I’m gonna remove the answer in a minute)

  • It does not work, however I was able to solve using the regular expression of your reply. Thank you.

  • @Filipemoraes, What kind of error do you get? What is your version of java? (I successfully tested with java 1.8.0_45), string "t" contains more than one line?

  • 1

    The code does not extract the Youtube ID as I reported in the question. I want to get the video ID and not remove it.

0


I found a reply in the Soen:

Using the regular expression .*youtube.com/./(.*?)%.* with the 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));
}

0

I believe 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.