Python正则表达式将youtube url转换为youtube视频 [英] Python regex convert youtube url to youtube video

查看:25
本文介绍了Python正则表达式将youtube url转换为youtube视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个正则表达式,以便我可以在用户发布的一段 HTML 文本中找到 youtube 链接(可以是多个).

I'm making a regex so I can find youtube links (can be multiple) in a piece of HTML text posted by an user.

目前我正在使用以下正则表达式将http://www.youtube.com/watch?v=-JyZLS2IhkQ"更改为显示相应的 youtube 视频:

Currently I'm using the following regex to change 'http://www.youtube.com/watch?v=-JyZLS2IhkQ' into displaying the corresponding youtube video:

return re.compile('(http(s|):\/\/|)(www.|)youtube.(com|nl)\/watch\?v\=([a-zA-Z0-9-_=]+)').sub(tag, value)

(其中变量标签"是一点点 html,因此视频可以正常工作并重视"用户帖子)

(where the variable 'tag' is a bit of html so the video works and 'value' a user post)

现在这有效..直到网址是这样的:

Now this works.. until the url is like this:

'http://www.youtube.com/watch?v=-JyZLS2IhkQ&feature...'

'http://www.youtube.com/watch?v=-JyZLS2IhkQ&feature...'

现在我希望你们能帮我弄清楚如何匹配&feature..."部分,使其消失.

Now I'm hoping you guys could help me figure how to also match the '&feature...' part so it disappears.

示例 HTML:

No replies to this post..

Youtube vid:

http://www.youtube.com/watch?v=-JyZLS2IhkQ

More blabla

感谢您的意见,非常感谢

Thanks for your thoughts, much appreciated

斯蒂芬

推荐答案

我是如何解决这个问题的:

Here how I'm solving it:

import re

def youtube_url_validation(url):
    youtube_regex = (
        r'(https?://)?(www\.)?'
        '(youtube|youtu|youtube-nocookie)\.(com|be)/'
        '(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})')

    youtube_regex_match = re.match(youtube_regex, url)
    if youtube_regex_match:
        return youtube_regex_match

    return youtube_regex_match

测试:

youtube_urls_test = [
    'http://www.youtube.com/watch?v=5Y6HSHwhVlY',
    'http://youtu.be/5Y6HSHwhVlY', 
    'http://www.youtube.com/embed/5Y6HSHwhVlY?rel=0" frameborder="0"',
    'https://www.youtube-nocookie.com/v/5Y6HSHwhVlY?version=3&hl=en_US',
    'http://www.youtube.com/',
    'http://www.youtube.com/?feature=ytca']


for url in youtube_urls_test:
    m = youtube_url_validation(url)
    if m:
        print('OK {}'.format(url))
        print(m.groups())
        print(m.group(6))
    else:
        print('FAIL {}'.format(url))

这篇关于Python正则表达式将youtube url转换为youtube视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆