The regex that you have is php-style regex, not java-style - for example, note /ig;
flags at the end.
So you'll just have to edit it a bit:
val youtubeRgx = """https?://(?:[0-9a-zA-Z-]+\.)?(?:youtu\.be/|youtube\.com\S*[^\w\-\s])([\w \-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>|</a>))[?=&+%\w-]*""".r
I tested it on all possible youtube urls, and it works. Example:
scala> youtubeRgx.pattern.matcher("http://www.youtube.com/watch?v=XrivBjlv6Mw").matches
res23: Boolean = true
And extracting the value:
"http://www.youtube.com/watch?v=XrivBjlv6Mw" match {
case youtubeRgx(a) => Some(a)
case _ => None
}
res33: Option[String] = Some(XrivBjlv6Mw)
It's a pity that java does not allow proper comments in regexps, so I did what I could:
val youtubeRgx = """https?:// # Required scheme. Either http or https.
|(?:[0-9a-zA-Z-]+\.)? # Optional subdomain.
|(?: # Group host alternatives.
| youtu\.be/ # Either youtu.be,
|| youtube\.com # or youtube.com followed by
| \S* # Allow anything up to VIDEO_ID,
| [^\w\-\s] # but char before ID is non-ID char.
|) # End host alternatives.
|([\w\-]{11}) # $1: VIDEO_ID is exactly 11 chars.
|(?=[^\w\-]|$) # Assert next char is non-ID or EOS.
|(?! # Assert URL is not pre-linked.
| [?=&+%\w]* # Allow URL (query) remainder.
| (?: # Group pre-linked alternatives.
| [\'"][^<>]*> # Either inside a start tag,
| | </a> # or inside <a> element text contents.
| ) # End recognized pre-linked alts.
|) # End negative lookahead assertion.
|[?=&+%\w-]* # Consume any URL (query) remainder.
|""".stripMargin.replaceAll("\\s*#.*\n", "").replace(" ","").r
(adapted from @ridgerunner's answer here: find all youtube video ids in string)