您拥有的正则表达式是 php 风格的正则表达式,而不是 java 风格的 - 例如,/ig;
最后的注释标志。
所以你只需要稍微编辑一下:
val youtubeRgx = """https?://(?:[0-9a-zA-Z-]+\.)?(?:youtu\.be/|youtube\.com\S*[^\w\-\s])([\w \-]{11})(?=[^\w\-]|$)(?![?=&+%\w]*(?:[\'"][^<>]*>|</a>))[?=&+%\w-]*""".r
我在所有可能的 youtube 网址上对其进行了测试,并且可以正常工作。例子:
scala> youtubeRgx.pattern.matcher("http://www.youtube.com/watch?v=XrivBjlv6Mw").matches
res23: Boolean = true
并提取价值:
"http://www.youtube.com/watch?v=XrivBjlv6Mw" match {
case youtubeRgx(a) => Some(a)
case _ => None
}
res33: Option[String] = Some(XrivBjlv6Mw)
遗憾的是java不允许在正则表达式中进行正确的注释,所以我做了我能做的:
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
(改编自@ridgerunner 在这里的回答:find all youtube video ids in string)