2

I need to get the video id of a YouTube url as follows. https://m.youtube.com/watch?v=9tg3csrFVJw I referred This and this but I could not find a solution.

any help is appreciated.

Community
  • 1
  • 1
Lak
  • 381
  • 1
  • 5
  • 23

2 Answers2

1

Try this regex:

v=([^\s&#]*)

Demo

Explanation:

  1. v= literally matches v=
  2. () capturing group , in this case group 1, whose value I want to capture here
  3. [^\s&#]* matches everything unless a space or & or #. & is necessary as the version id may not be the last parameter. # is necessary as # can be used as bookmark in a url.

You can try that :

    final String regex = "v=([^\\s&#]*)";
    final String string = " https://m.youtube.com/watch?v=9tg3csrFVJw";
    final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
    final Matcher matcher = pattern.matcher(string);

    if(matcher.find()) {
        System.out.println(matcher.group(1));
    }

Run it here

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
0

You can use

val regex =
        "^((?:https?:)?//)?((?:www|m)\\.)?((?:youtube\\.com|youtu.be|youtube-nocookie.com))(/(?:[\\w\\-]+\\?v=|feature=|watch\\?|e/|embed/|v/)?)([\\w\\-]+)(\\S+)?\$"

Please refer the link to know more.

Nick
  • 195
  • 1
  • 5