2

I want to create a regex where url given will output me video id. I know that youtube id always has 11 characters, my regex kind of works, but it doesn't work when someone shared a video which is already played: i.e when you open a video it starts at x of seconds.

Please view my example here:

https://regex101.com/r/kgVkTE/1

([0-9A-Z{11}])\w+

Example url:

https://www.youtube.com/watch?v=MI9tFPT6yK4&t=17s
https://www.youtube.com/watch?v=48Y_jWQDDiw
https://www.youtube.com/MI9tPtdas5
https://www.youtube.com/9MI9tPtdas5
Przemyslaw Wojtas
  • 301
  • 3
  • 7
  • 18

2 Answers2

0

I'm assuming based on your description that the ID will always have 11 characters. If that is always the case then you can simply use:

\w{11}
  • \w represents alphabets, numbers and underscore
  • {11} makes sure 11 such characters appear

However, your examples has one with 10 characters, for that:

\w{10,11}

Regex101 Demo

degant
  • 4,466
  • 1
  • 13
  • 28
0

As per your input strings, you could use:

(?<=v=|/)\w{10,11}

See your modified demo on regex101.com.
This requires either v= or a / right before ten or eleven word characters.

Jan
  • 38,539
  • 8
  • 41
  • 69