使用正则表达式查找不包含特定

2024-04-28 23:43:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用python3.5和re模块开发scraper/webcrawler,其中一个函数需要检索YouTube频道的URL。我将使用以下代码部分(包括正则表达式的匹配)来实现这一点:

href = re.compile("(/user/|/channel/)(.+)")

它应该返回/user/username/channel/channelname之类的内容。它在很大程度上成功地做到了这一点,但是它时不时地获取一种URL类型,其中包含更多的信息,比如/user/username/videos?view=60或者username/部分后面的其他信息。你知道吗

为了解决这个问题,我将上面的代码重写为

href = re.compile("(/user/|/channel/)(?!(videos?view=60)(.+)")

以及其他没有成功的变化。我如何重写我的代码,使它获取的URL不包括videos?view=60在URL的任何地方?你知道吗


Tags: 模块函数代码review信息urlchannel
2条回答

对特定的regex模式使用以下方法:

user_url = '/user/username/videos?view=60'
channel_url = '/channel/channelname/videos?view=60'

pattern = re.compile(r'(/user/|/channel/)([^/]+)')

m = re.match(pattern, user_url)
print(m.group())    # /user/username

m = re.match(pattern, channel_url)
print(m.group())    # /channel/channelname

我用这种方法,它似乎做你想要的。你知道吗

import re

user = '/user/username/videos?view=60'
channel = '/channel/channelname/videos?view=60'

pattern = re.compile(r"(/user/|/channel/)[\w]+/")

user_match = re.search(pattern, user)

if user_match:
    print user_match.group()
else:
    print "Invalid Pattern"

pattern_match = re.search(pattern,channel)

if pattern_match:
    print pattern_match.group()
else:
    print "Invalid pattern"

希望这有帮助!你知道吗

相关问题 更多 >